我正在对组件进行单元测试,该组件将呈现来自服务器的代码列表。
响应是这种格式:
{
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)
);
}
它工作正常,我可以使用component.html文件显示数据:
..
...
<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.spec文件时,它给我一个错误:
TypeError: Cannot read property 'length' of undefined
我意识到在.html中,由于长度为codesArray
,所以我的undefined
是undefined
。
我console
我的codesArray
。它在comp.ts文件中显示数据,但在comp.spec文件中显示undefined
不知道我在做什么错,因为我能够正确呈现数据,但是由于某种原因我的测试失败了。这是我的component.spec文件
..
...
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();
});
});
谢谢。
在MockCodesService
中,getCodes()
从数组中返回一个可观察对象,但在组件中,this.service.getCodes()
期望从具有ContactActivityView
属性的对象中观察到。尝试在MockCodesService
中执行类似的操作:
getCodes(): Observable<ICodeModel[]> {
return of({
ContactActivityView :[
{
Code:"AB",
IsActive:false,
},
{
Code:"BC",
IsActive:true,
}]
});
}