我正在测试一个组件说:导出和导入使用名为uploadService.ts
的服务的文件uploadService有一个方法sendFile,它由组件方法importRules()在内部调用。
uploadService.ts
@Injectable()
export class UploadService {
constructor(private http: Http, private sharedData: SharedDataService) { }
sendFile(file: File, groupName?: string): Observable<Response> {
…
return this.http.post(url, data, options);
}
}
exportImport.components.ts
ImportRules() {
this.uploadService.sendFile(fileObj, fileName) {
…
}
}
对应的spec文件 的 exportImport.components.spec.ts
class MockUploadService extends UploadService {
constructor() {
super(null, null);
}
sendFile(file: File, groupName?: string): Observable<Response> {
let resObject = new Response(null);
resObject.status = 200;
return Observable.of(resObject);
}
}
在之前,我已经用模拟服务取代了真正的服务
it('should import ioc rules',
async(() => {
TestBed
.compileComponents()
.then(() => {
let fixture = TestBed.createComponent(TestComponent);
// let http = new ConnectionBackend();
let exportImportInstance = fixture.debugElement.children[0].componentInstance;
let mockReq: MockUploadService = new MockUploadService();
exportImportInstance.setGroupName('test');
exportImportInstance.setChosenFile('file.json');
spyOn(mockReq, 'sendFile');
exportImportInstance.importRules();
expect(mockReq.sendFile).toHaveBeenCalledWith('file.json', 'test');
});
}));
但是在执行测试时我遇到了错误:
使用['file.json','test']调用预期的间谍sendFile但从未调用过。
我不知道我在这里做错了什么。
答案 0 :(得分:3)
以下列方式使用spyOn:
let fixture = TestBed.createComponent(TestComponent);
const mockResponse = { 'name': 'uploaded' };
let spy: jasmine.Spy = spyOn(mockUploadService,'sendFile').and.returnValue(Observable.of(
new Response(new ResponseOptions({ body: mockResponse }))));
expect(spy.calls.any()).toBe(true, 'spy send file of upload is called');
expect(spy.calls.first().args[0]).toBe('file.json');