请你检查下面的测试,看看为什么间谍永远不会被召唤?实际代码工作正常,但测试没有播放。
如果spyOn
内有this.apiSrv.fetch
的内容,那么测试通过了。很奇怪!
提前谢谢。
manager.service.spec.ts
describe('ManagerService', () => {
const mockClass = new MockClass();
let spy;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
ManagerService,
{ provide: ApiService, useValue: mockClass},
]
});
spy = spyOn(mockClass, 'fetch');
});
fit('should call server', inject([ManagerService], (service: ManagerService) => {
service.callServer();
expect(spy).toHaveBeenCalled();
}));
});
manager.service.ts
@Injectable()
export class ManagerService {
constructor(
private apiSrv: ApiService,
) {}
public callServer() {
this.apiSrv.fetch('http://url.com').subscribe( (data) => {
console.log(data);
});
}
}
api.service.ts
export class ApiService {
constructor(private http: Http) {}
fetch(resource: string) {
return this.http.get(resource).map((response) => response.json());
}
}
mock.ts
export class MockClass {
public fetch(): Observable<any> {
const expectedResult = {
items: {
data: [],
}
};
return Observable.of( expectedResult );
}
}
结果:
答案 0 :(得分:1)
您需要确保实际调用MockClass.fetch
medhod(而不仅仅是stubbed),因为您使用.subscribe
方法链接它,否则会导致错误并且不会传递测试。所以应该使用callThrough
。
spy = spyOn(mockClass, 'fetch').and.callThrough();
^^^^^^^^^^^^^^^^^^
add this