我有这段代码:
/**
* Attempt login with provided credentials
* @returns {Observable<number>} the status code of HTTP response
*/
login(username: string, password: string): Observable<number> {
let body = new URLSearchParams();
body.append('grant_type', 'password');
body.append('username', username);
body.append('password', password);
let connObservable = this.http.post(Constants.LOGIN_URL, body, null)
.map(res => {
if (res.status == 200) {
log(res.json());
}
return res.status;
})
.catch(err => { return Observable.throw(err.status) })
.publish();
// this ensures that side effects will be present regardless os whether
// the client subscribes to the returned Observable
connObservable.connect();
// no need for the client to know that we use ConnectableObservable internally
return connObservable as Observable<number>;
}
我想使用此代码对其进行单元测试:
describe('AuthenticationService', () => {
let sut: AuthenticationService;
let authTokeServiceStub: AuthTokenServiceStub;
let mockBackend: MockBackend;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ HttpModule ],
providers: [
AuthenticationService,
{provide: XHRBackend, useClass: MockBackend},
{provide: AuthTokenService, useClass: AuthTokenServiceStub}
]
});
sut = TestBed.get(AuthenticationService);
authTokeServiceStub = TestBed.get(AuthTokenService);
mockBackend = TestBed.get(XHRBackend);
});
describe('login()', () => {
it('should store retrieved access token on successful response', () => {
mockBackend.connections.subscribe(connection => {
let options = new ResponseOptions();
options.body = JSON.stringify({access_token : 'accessToken'});
options.status = 200;
connection.mockRespond(new Response(options));
});
spyOn(authTokeServiceStub, 'setAuthToken');
sut.login('username', 'password');
expect(authTokeServiceStub.setAuthToken).toHaveBeenCalledWith('accessToken');
});
});
});
问题是log(res.json())
总是产生空对象:{}
。
为了隔离问题,我试图将模拟响应的状态更改为400,但它没有任何效果。看起来options
对象的Response
参数被忽略了。
我尝试将测试包装在async
中,然后插入fakeAsync
并在各个阶段之间添加tick()
和tick(50)
,但它也不起作用。
我做错了什么?
答案 0 :(得分:0)
您需要更新对
的回复new Response(new ResponseOptions(response))