Search code examples
angularjsangularkarma-jasmineangular2-testing

How to add providers in angular2 jasmine testing spec since addProvider is deprecated in RC6?


I am trying to write my beforeEach like this so that every it gets the required modules / providers:

beforeEach(() => addProviders([
        BaseRequestOptions,
        MockBackend,
        {
            provide: Http,
            useFactory: (backend: MockBackend, options: BaseRequestOptions) => new Http(backend, options),
            deps: [MockBackend, BaseRequestOptions]
        },
        MyService
    ]));

But since addProviders method is deprecated in RC6, what is a better alternative to add my providers?


Solution

  • Use TestBed from @angular/core/testing to create test modules. For example

    beforeEach(() => {
      TestBed.configureTestingModule({
        imports: [ ... ],
        declarations: [ ... ],
        providers: [
          { .. },
          MyService
        ]
      });
    });
    

    It's pretty much the same as configuring a regular module except you don't need to export anything.

    See more complete examples in the ng2-test-seed. It has examples of testing components also using the TestBed