首页 文章

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

提问于
浏览
0

我没有特定于组件 - 但是,我发现了一些文章(例如,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

    使用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');
      });
    }));
    

相关问题