Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing angular ngmodule

Tags:

module

angular

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.

like image 712
Miroslav Jonas Avatar asked Jul 06 '17 13:07

Miroslav Jonas


1 Answers

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.

like image 55
Lars Gyrup Brink Nielsen Avatar answered Nov 11 '22 17:11

Lars Gyrup Brink Nielsen