我正在尝试为此调用Jasmine建立一个模拟测试。
由于调用handleSuccess
方法而失败,但响应为undefined
。
AuthenticationService
代码:
public login(cred): Observable<any> {
const data = {};
return this.http.post(this.url, data, { observe: 'response' }).map(
response => this.handleSuccess(response)
);
}
测试代码:
describe('AuthenticationService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
AuthenticationService,
{ provide: HttpClient, useClass: MockHttpClient }
]
});
});
it('should be created', inject([AuthenticationService], (service: AuthenticationService) => {
spyOn<any>(service, 'handleSuccess').and.callThrough();
expect(service).toBeTruthy();
service.login({userId: 'XY12345', userPassword: 'password'})
.subscribe((resp) => {
expect(service['handleSuccess']).toHaveBeenCalled();
});
}));
});
class MockHttpClient {
post(url: string, body: any, options: any) {
return Observable.of({
response: {
headers: {},
body: {}
}
});
}
}