我试图模拟身份验证服务。我发布我的登录凭据并获得一个令牌,然后保存令牌。
如果我评论该行,基本上测试运行:
this.authenticationService.saveToken(res.json().token);
我在测试中注入了服务,这行不会影响输出。
我的错误是"无法读取属性' saveToken'未定义的抛出"
这是我的服务:
private authSuccess(res: Response){
this.isAuthenticated = true;
this.authenticationService.saveToken(res.json().token);
return res.json();
}
public postLogin(loginData: LoginModel): Observable<any>{
let body = JSON.stringify(loginData);
var headers = new Headers();
headers.append('Content-Type', 'application/json');
let options = new RequestOptions({ headers: headers });
return this.http.post(this.loginUrl, body, options)
//success
.map(this.authSuccess)
//error
.catch(this.handleError);
}
这是我的测试:
describe('login service tests', () => {
let loginService: LoginService;
let backend: MockBackend;
let injector: Injector;
let authenticationService: AuthenticationService;
beforeEach(() => {
injector = ReflectiveInjector.resolveAndCreate(<any> [
LoginService,
AuthenticationService,
BaseRequestOptions,
MockBackend,
provide(Http, {
useFactory: (mockBackend, defaultOptions) => new Http(mockBackend, defaultOptions),
deps: [MockBackend, BaseRequestOptions]
})
]);
loginService = <LoginService> injector.get(LoginService);
backend = <MockBackend> injector.get(MockBackend);
authenticationService = <AuthenticationService> injector.get(AuthenticationService)
});
afterEach(() => backend.verifyNoPendingRequests());
it('should authenticate with the web api', () => {
let loginUrl = Constants.loginUrl;
let loginData:LoginModel = new LoginModel('username', 'password');
backend.connections.subscribe((c: MockConnection) => {
expect(c.request.url).toEqual(loginUrl);
c.mockRespond(new Response(new ResponseOptions({ body: '{"token": "mockAuth"}' })));
});
//Correct login data
loginService.postLogin(loginData).subscribe((data) => {
expect(data.token).toBe('mockAuth');
});
});
另外,你们在运行测试时如何调试? console.log似乎不起作用,也没有调试器;
答案 0 :(得分:0)
好吧,所以似乎问题是调用.map部分中的方法而不是直接在那里执行所有操作。
解决方案:
删除authsuccess
.map((response) => {
this.isAuthenticated = true;
this.authenticationService.saveToken(response.json().token);
return response.json();
})