你如何在Angular 2.0中测试组件?

时间:2016-08-12 15:47:59

标签: angular

我正在尝试为Angular 2.0组件设置一些单元测试。虽然Angular 2.0网站上的文档包含使用Jasmine进行一般单元测试的信息,但没有任何组件特定 - 但是,我发现了一些文章(例如,https://medium.com/google-developer-experts/angular-2-unit-testing-with-jasmine-defe20421584),参考使用" angular2 / testing"促进依赖注入和组件测试。

但是,我可以找到的最新参考是针对测试版,而不是最近的RC版本之一:https://code.angularjs.org/2.0.0-beta.9/testing.dev.js

是否有人知道使用此正确或首选的是否可以作为在Angular 2.0中进行组件测试的方法?

编辑:为了澄清,我只是在寻找一种测试功能组件的方法,我已经更新了上面的问题以反映这一点。

编辑2:看起来TestComponentBuilder(angular.io/docs/ts/latest/api/core/testing/TestComponentBuilder-class.html)适合我所寻找的东西,但是它是弃用。

1 个答案:

答案 0 :(得分:0)

使用Angular 2 rc.5,试试这个(这个例子使用TestBed):

import { provide } from '@angular/core';
import { async, TestBed } from '@angular/core/testing';

import { SomeComponent } from './some.component';

beforeEach(() => {
  TestBed.configureTestingModule({
    declarations: [
      SomeComponent
    ],
    providers: [
      SomeComponent,
      // ServiceA,
      // provide(ServiceB, { useClass: TestServiceB })
    ],
    imports: [
      // HttpModule,
      // etc.
    ]
  });
});

it('should do something', async(() => {
  // Overrides here, if you need them:
  TestBed.overrideComponent(SomeComponent, {
    set: {
      template: '<div>Overridden template here</div>'
      // ...
    }
  });

  TestBed.compileComponents().then(() => {
    const fixture = TestBed.createComponent(SomeComponent);

    // Access the dependency injected component instance:
    const app = fixture.componentInstance;

    // Access the element
    const element = fixture.nativeElement;

    // Detect changes to wire up the `fixture.nativeElement` as necessary:
    fixture.detectChanges();

    expect(app.something).toBe('something');
  });
}));
相关问题