Is there a way to test NgModule in Angular 2/4 (e.g. test forRoot and forChild)? All the tutorials and docs only refer to components, services, pipes and directives.
I have a module with rather complex functionality and would like to test it.
Examples from the Medium article Angular Testing Snippets: @NgModule providers - Writing spec files for Angular Modules and exported providers by David Herges.
import { TestBed } from '@angular/core/testing';
import { FeatureModule } from './feature.module';
import { CustomHttp } from './custom-http.service';
describe(`FeatureModule`, () => {
    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [ FeatureModule ]
        });
    });
    it(`should not provide 'CustomHttp' service`, () => {
        expect(() => TestBed.get(CustomHttp)).toThrowError(/No provider for/);
    });
});
describe(`FeatureModule.forRoot()`, () => {
    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [
                HttpModule,
                FeatureModule.forRoot()
            ]
        });
    });
    it(`should provide services`, () => {
        expect(TestBed.get(CustomHttp)).toBeTruthy();
    });
    it(`should provide a single instance for 'CustomHttp' and 'Http' injection tokens`, () => {
        const http: Http = TestBed.get(Http);
        const customHttp: CustomHttp = TestBed.get(CustomHttp);
        // both should be same instance
        expect(http).toBe(customHttp);
        /* USE CASE: `@Inject(Http)` and `@Inject(CustomHttp)`
         * PROVIDER / MODULE:
         * providers: [ { provide: CustomHttp, useClass: CustomHttp },
         *              { provide: Http, useExisting: CustomHttp } ]
         */
    });
});
These examples test the providers of an NgModule when imported in a feature module as well as the root module.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With