测试角度ngmodule

Mir*_*nas 5 module angular

有没有办法在Angular 2/4中测试NgModule(例如test forRoot和forChild)?所有的教程和文档仅涉及组件,服务,管道和指令。

我有一个功能相当复杂的模块,想对其进行测试。

Lar*_*sen 7

中篇文章Angular Testing Snippets中的示例:@NgModule provider-由David Herges 编写Angular模块的规范文件和导出的provider。

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 } ]
         */
    });

});
Run Code Online (Sandbox Code Playgroud)

这些示例测试了将NgModule的提供程序导入到功能模块以及根模块中时的情况。