Angular2 http调用使测试执行两次

时间:2016-04-15 08:41:55

标签: javascript unit-testing typescript angular

我有一个带有简单组件的Angular2应用程序

@Component({
  selector: 'Techs',
  template: '',
  providers: [HTTP_PROVIDERS]
})
export class Techs {
  public techs: Tech[];

  constructor(http: Http) {
    http
      .get('src/app/techs/techs.json')
      .map(response => response.json())
      .subscribe(result => this.techs = result);
  }
}

我的测试执行了两次:

  

Chrome 49.0.2623(Mac OS X 10.11.4):执行0成功6(0秒/ 0秒)

     

日志:'测试结束'

     

Chrome 49.0.2623(Mac OS X 10.11.4):成功执行6 6成功(0.182秒/ 0.153秒)

但是,如果我删除了Http调用,则测试只执行一次

  

Chrome 49.0.2623(Mac OS X 10.11.4):成功执行6 6成功(0.182秒/ 0.153秒)

这是我的测试

describe('techs component', () => {
  it('should render 3 elements <tech>', injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => {
    return tcb
      .createAsync(Techs)
      .then(fixture => {
        fixture.componentInstance.techs = [{}, {}, {}];
        fixture.detectChanges();
        const techs = fixture.nativeElement;
        expect(techs.querySelectorAll('tech').length).toBe(3);
      });
  }));
});

1 个答案:

答案 0 :(得分:0)

我认为您的问题来自HTTP调用的异步方面。我会看到两种解决方法:

  • 另一种方法是模拟你的Http对象以模拟HTTP调用。这可以使用MockBackend类来完成。

以下是针对XHRBackend类配置它:

beforeEachProviders(() => {
  return [
    HTTP_PROVIDERS,
    provide(XHRBackend, { useClass: MockBackend }),
 ];
});

以及在响应中返回所需内容的方法:

it('Should return a list of dogs', inject([XHRBackend, HttpService, Injector], (mockBackend, httpService, injector) => {
  mockBackend.connections.subscribe(
    (connection: MockConnection) => {
      connection.mockRespond(new Response(
        new ResponseOptions({
          body: [ { name: 'test' }, ... ]
      })));
    }
    (...)