我正在运行一个失败的单元测试。请看我的代码:
这是我的打字稿文件:
allData: any;
constructor(@Inject(MAT_DIALOG_DATA) private data,
private dialogRef: MatDialogRef<MyComponent>,
private _service: SampleService,
private _router: Router) {
}
ngOnInit() {
this.loadValue();
}
loadValue() {
this._service.returnData().subscribe(res => {
this.allData = res;
})
}
这是我的服务文件实现:
//SampleService
returnData(){
const users=[{ id: "01", name:"Andrew" }, { id: "02", name:"Shaun" }];
return of(users);
}
这是我的规格文件:
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
let el: DebugElement;
let sampleservice: SampleService;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [MyComponent],
schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA],
imports: [MatDialogModule],
providers: [
{
provide: MAT_DIALOG_DATA, useValue: { action: "add" },
},
{
provide: MatDialogRef, useValue: { MyComponent}
},
{
provide: Router
},
{
provide: SampleService
}
]
}).compileComponents()
}));
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
el = fixture.debugElement;
component = fixture.componentInstance;
sampleservice = new SampleService();
})
我的测试用例:
it("should call the loadvalue and fill the allData", () => {
let users = [{ id: "01", name: "John" }, { id: "02", name: "Wick" }];
component.loadValue();
spyOn(sampleservice, 'returnData').and.returnValue(of(users));
expect(component.allData).toBe(users);
})
我想调用该loadvalue()
方法并期望allData
使用spyOn
. 但是当我运行这个测试用例时,我得到错误:
TypeError:无法读取未定义的属性“returnData”
我在这里做错了什么?任何帮助将非常感激。谢谢!