是否有一个 optimal way to define imports, declarations, providers common to all spec.ts (即一个地方定义的所有规范所共有的模块,就像我们在@NgModule中所做的那样)在一个地方就像我们在@NgModule中为应用程序 Unit tests 所做的那样 .
注意:在beforeEach中调用configureTestingModule,以便TestBed可以在每次测试运行之前将自身重置为基本状态 . 就像文件一样
在我的一个测试规范中,我必须加载相同的模块组件和指令..etc,这也被其他一些规范使用 .
describe('Component: Login', () => {
let loginFixture, loginComponent, loginComponentElement,loginComponentDebugElement;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [FormsModule, ReactiveFormsModule, MaterialRootModule, ModalModule, DatepickerModule,
DropdownModule, AccordionModule], //--> here we load n number of mudoles
declarations: [LoginComponent, LoginHeaderComponent, LoginColumnComponent, LoginColumnContentComponent,
LoginStatusLaneComponent, LoginSettingsComponent,
LoginLaneComponent, SortableDirective, WindowHeightDirective, ConfirmDirective, ConfirmPopoverComponent, ConfirmationDialogComponent,
ConfirmationDialogDirective], //--> here we load n number of components directive and piper
providers: [LoginComponent,
MockBackend,
BaseRequestOptions,
ComponentLoaderFactory,
ConfirmOptions,
{
provide: Http,
useFactory: (backend, options) => new Http(backend, options),
deps: [MockBackend, BaseRequestOptions]
},
{provide: AuthService, useClass: MockAuthService},
{provide: AppContextService, useClass: MockAppContextService},
{provide: NotificationsService, useClass: MockNotificationsService},
{provide: PositioningService}] //--> here we load n number of services
}).compileComponents();
loginFixture = TestBed.createComponent(LoginComponent);
loginComponent = loginFixture.componentInstance;
loginComponentElement = LoginFixture.nativeElement;
loginComponentDebugElement = LoginFixture.debugElement;
}));
it('should have a defined component', () => {
expect(LoginComponent).toBeDefined();
});
});
注意:Git Angular issue TestBed.configureTestingModule Performance Issue
Is there any pattern to make it common like loading all this modules components etc in starting before running all spec.ts 文件并为每个规范注入相应的依赖项 . 任何帮助都会很棒 .
2 回答
你的回答是不完整的,你已经开始期待了 . 但我希望它能帮到你一点点 .
路由器stubs.ts
每个test.spec.ts
但是提供者/声明不能以相同的方式使用 .
您需要在describe方法之前定义TestBed.configureTestingModule . 所以它可以在全球范围内使用 . 所以现在你的测试用例看起来像这样 .