Angular 2 AND Karma测试和异步HTTP

时间:2016-01-26 20:12:04

标签: http testing asynchronous angular karma-jasmine

所以我的问题很容易解释

这是我的测试规范

import {
  describe,
  expect,
  it,
  inject,
  beforeEachProviders
} from 'angular2/testing_internal';
import {RestClient} from './rest.service';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/delay';
import {
  HTTP_PROVIDERS
} from 'angular2/http';
export function main() {
   describe('RestClient Service', () => {
      beforeEachProviders( () => [HTTP_PROVIDERS, RestClient] );
      it('is defined', inject( [RestClient], (client) =>{
         client.get('http://jsonplaceholder.typicode.com/posts/1')
         .delay(2000)
         .toPromise()
         .then((res) => {
            console.log('test');
            expect(res.length).toBeGreaterThan(1000);
         });
       }));
    });
  }

这是“RestClient”类中返回Observable

的方法
public get(url:string): Observable<any> {
    return this.http.get(url).map(res => res.json());
}

所以,我开始测试和测试返回

START:
LOG: 'ciao'
RestClient Service
    ✔ is defined
PhantomJS 2.0.0 (Mac OS X 0.0.0) LOG: 'ciao'

Finished in 0.026 secs / 0.038 secs

SUMMARY:
   ✔ 2 tests completed

对于Karma一切正常并且测试正确传递并且不是真的,同时如果我将console.log放入“then”,则永远不会被调用。 索姆我认为这是异步调用的问题,你知道如何在Angular2异步调用中测试 我也使用过Inject和AsyncInject。 我知道我可以使用MockBackend,但我需要使用外部网址进行测试

提前感谢您的帮助

1 个答案:

答案 0 :(得分:0)

injectAsync应解决您的问题,但您需要退回承诺:

it('is defined', injectAsync( [RestClient], (client) =>{
  return client.get('http://jsonplaceholder.typicode.com/posts/1')
  .delay(2000)
  .toPromise()
  .then((res) => {
     console.log('test');
     expect(res.length).toBeGreaterThan(1000);
  });
}));