简体   繁体   中英

How do you test components in Angular 2.0?

I'm trying to setup some unit tests for Angular 2.0 components. While the documentation on the Angular 2.0 website has information for general unit testing using Jasmine, there's nothing component specific -- however, I've found a couple of articles (eg, https://medium.com/google-developer-experts/angular-2-unit-testing-with-jasmine-defe20421584 ), that reference using "angular2/testing" to facilitate dependency injection and component testing.

However, the latest reference I can find to this is for the beta, not one of the more recent RC versions: https://code.angularjs.org/2.0.0-beta.9/testing.dev.js

Does anyone know if using this still the correct or preferred works as a way to do component testing in Angular 2.0?

Edit: To clarify, I am simply looking for a method to test components that functions and I have updated my question above to reflect this.

Edit 2: It looks like the TestComponentBuilder (angular.io/docs/ts/latest/api/core/testing/TestComponentBuilder-class.html) fits what I'm looking for, but it's deprecated.

With Angular 2 rc.5, try this out (this example uses 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');
  });
}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM