gpt4 book ai didi

angular - 测试 Angular ngmodule

转载 作者:太空狗 更新时间:2023-10-29 17:33:37 25 4
gpt4 key购买 nike

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

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

最佳答案

Medium 文章中的示例 Angular Testing Snippets: @NgModule providers - Writing spec files for Angular Modules and exported providers 来自 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 } ]
*/
});

});

这些示例在将 NgModule 的提供者导入功能模块和根模块时测试它们。

关于angular - 测试 Angular ngmodule,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44950826/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com