Angular2 测试异步 Http.MockBackend.connections 承诺不屈服
Angular2 test async Http.MockBackend.connections promise not yielding
我在使用 injectAsync
和 http.MockBackend
时遇到问题。 auth.ngOnInit()
方法调用 Http.get()
,但在本次测试中从未调用 MockBackend.connections.toPromise().then()
方法:
it('should check if the user is authenticated',
injectAsync([Auth, MockBackend], (auth, backend) => {
let promise = backend.connections.toPromise().then(
(connection) => {
let link = document.createElement('a');
link.href = connection.request.url;
expect(link.pathname).toBe('/api/auth/user/');
});
auth.ngOnInit();
return promise;
}));
我已经在调试器中确认正在调用 MockBackend.connections.next()
方法。然而,当我 运行 测试时,它失败了 Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
我在这里错过了什么?
感谢@alxhub 和@ericmartinezr in gitter,问题是我需要在调用 toPromise()
之前将可观察范围缩小到单个结果。所以这有效:
it('should check if the user is authenticated',
injectAsync([Auth, MockBackend], (auth, backend) => {
let promise = backend.connections.first().toPromise().then(
(connection) => {
let link = document.createElement('a');
link.href = connection.request.url;
expect(link.pathname).toBe('/api/auth/user/');
});
auth.ngOnInit();
return promise;
}));
我在使用 injectAsync
和 http.MockBackend
时遇到问题。 auth.ngOnInit()
方法调用 Http.get()
,但在本次测试中从未调用 MockBackend.connections.toPromise().then()
方法:
it('should check if the user is authenticated',
injectAsync([Auth, MockBackend], (auth, backend) => {
let promise = backend.connections.toPromise().then(
(connection) => {
let link = document.createElement('a');
link.href = connection.request.url;
expect(link.pathname).toBe('/api/auth/user/');
});
auth.ngOnInit();
return promise;
}));
我已经在调试器中确认正在调用 MockBackend.connections.next()
方法。然而,当我 运行 测试时,它失败了 Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
我在这里错过了什么?
感谢@alxhub 和@ericmartinezr in gitter,问题是我需要在调用 toPromise()
之前将可观察范围缩小到单个结果。所以这有效:
it('should check if the user is authenticated',
injectAsync([Auth, MockBackend], (auth, backend) => {
let promise = backend.connections.first().toPromise().then(
(connection) => {
let link = document.createElement('a');
link.href = connection.request.url;
expect(link.pathname).toBe('/api/auth/user/');
});
auth.ngOnInit();
return promise;
}));