TestBed Configuration (Optional)

As you will see in Testing Components, real-world component testing often relies on the Angular2 testing utility TestBed, which requires some configuration. Most significantly, we need to use TestBed.initTestEnvironment to create a testing platform before we can use unit tests with TestBed. This testing environment would have to be created, destroyed and reset as appropriate before every unit test.

In the angular2-redux-starter, this configuration is done in a tests.configure.ts file and imported into every unit test for easy re-use.

  1. import {
  2. getTestBed,
  3. ComponentFixtureAutoDetect,
  4. TestBed,
  5. } from '@angular/core/testing';
  6. import {
  7. BrowserDynamicTestingModule,
  8. platformBrowserDynamicTesting,
  9. } from '@angular/platform-browser-dynamic/testing';
  10. export const configureTests = (configure: (testBed: TestBed) => void) => {
  11. const testBed = getTestBed();
  12. if (testBed.platform == null) {
  13. testBed.initTestEnvironment(
  14. BrowserDynamicTestingModule,
  15. platformBrowserDynamicTesting());
  16. }
  17. testBed.configureCompiler({
  18. providers: [
  19. {provide: ComponentFixtureAutoDetect, useValue: true},
  20. ]
  21. });
  22. configure(testBed);
  23. return testBed.compileComponents().then(() => testBed);
  24. };

tests.configure.ts creates the testing platform if it doesn't already exist, compiles the template, and exports configureTests which can then be imported and used in our unit tests.

Here's a look at how it would be used:

  1. import { TestBed } from '@angular/core/testing';
  2. import { ExampleComponent } from './index';
  3. import { configureTests } from '../../tests.configure';
  4. import { AppModule } from '../../modules/app.module';
  5. describe('Component: Example', () => {
  6. let fixture;
  7. beforeEach(done => {
  8. const configure = (testBed: TestBed) => {
  9. testBed.configureTestingModule({
  10. imports: [AppModule],
  11. });
  12. };
  13. configureTests(configure).then(testBed => {
  14. fixture = testBed.createComponent(ExampleComponent);
  15. fixture.detectChanges();
  16. done();
  17. });
  18. });

原文: https://angular-2-training-book.rangle.io/handout/testing/intro-to-tdd/setup/testbed-configuration.html