Я тестирую модуль, который выводит список кодов с сервера.
Ответ приходит в следующем формате:
{
ContactActivityView :[
{
Code:"AB",
IsActive:false,
},
{
Code:"BC",
IsActive:true,
}
..
...
]
}
В моем файле component.ts я использую его следующим образом:
codesArray: ICodeModel[];
ngOnInit() {
this.getCodes();
}
getCodes() {
this.service.getCodes()
.subscribe((response: ICodeModel[] | []) => {
this.codesArray = response['ContactActivityView'];
},
error => console.log(error)
);
}
Он работает нормально, и я я могу показать мои данные, используя компонент. html file:
..
...
<div class="message" *ngIf="codesArray.length === 0">
No Data Found.
</div>
<div class="tbl-row" *ngFor="let code of codesArray">
<div class="item">
{{ code.Code }}
</div>
<div class="item">
{{ code.IsActive }}
</div>
..
...
файл component.service:
..
...
getCodes(): Observable<ICodeModel[]> {
return this._service.get(this.codeURL);
}
..
...
Теперь, когда я запускаю свой component.spe c file it выдает ошибку:
TypeError: Cannot read property 'length' of undefined
Я понял, что в. html my codesArray
равен undefined
, из-за которого длина равна undefined
.
I console
my codesArray
. Он показывает данные в файле comp.ts, но приходит undefined
в файле comp.spe c
Не уверен, что я делаю неправильно, поскольку я могу правильно отобразить данные, но каким-то образом мой тест терпит неудачу. Вот мой компонент.spe c file
..
...
class MockCodesService {
getCodes(): Observable<ICodeModel[]> {
return of([]);
}
addCode(param: ICodeModel){
return of({});
}
updateCode(param: ICodeModel) {
return of({});
}
}
describe('CodesComponent', () => {
let component: CodesComponent;
let fixture: ComponentFixture<CodesComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
CodesComponent
],
providers: [
{ provide: CommonCrudService, useClass: CommonCrudMockService },
{ provide: MessageService, useClass: MessageMockService },
{ provide: AppService, useClass: AppMockService },
{ provide: CodesService, useClass: MockCodesService }
],
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(CodesComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
Спасибо.