【发布时间】:2021-10-15 05:38:11
【问题描述】:
我正在努力为以下代码编写一个成功的测试用例。
在component.ts中
id = 123456;
data = [];
constructor(private serv: ApiService){}
ngOnInint(){
getData(id);
}
getData(id){
this.serv.getRequest(url+id).subscribe({
(res){
this.data = res;
});
}
在 spec.ts 文件中
describe('component', () =>{
let component: DataComponent,
let fixture: ComponentFixture<OpenCasesComponent>;
let serv: ApiService;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports:[HttpClientTestingModule],
declartions:[DataComponent],
Providers: [ApiService]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.CreateComponent(DataComponent);
component = fixture.componentInstance;
apiService = TestBed.inject(ApiService);
fixture.detectChanges();
});
it('should make api call on load', fakeAsync(()=>{
component.id = '123456';
let fakeResponse = {
name: 'John';
}
component.ngOnInit();
fixture.detectChanges();
spyOn(component, 'getData').withArgs('123456').and.callThrough();
spyOn(apiService, 'getRequest')..and.returnValue(of(fakeResponse));
fixture.detectChanges();
tick();
expect(component.getData).toHaveBeenCalled();
expect(apiService.getRequest).toHaveBeenCalled();
expect(component.data).toContain(fakeResponse);
}));
}
类似的函数调用适用于类似的代码。不同之处在于,该功能是由单击按钮触发的。我的猜测是我这里没有调用函数,如果是我该怎么做。
我做错了什么?
【问题讨论】:
标签: javascript angular typescript jasmine karma-jasmine