我在将injectAsynchttp.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;
}));

10-04 13:21