是否有一种最佳方式来定义所有 spec.ts 通用的导入、声明、提供程序(即所有规范通用的模块,一个地方定义就像我们在@NgModule 中所做的那样)在一个地方,比如我们在@NgModule 中为应用单元测试做。
注意:在 beforeEach 中调用 configureTestingModule 以便 TestBed 可以在每次测试运行之前将自身重置为基本状态。如文档所示
在我的一个测试 spec.ts 中,我必须加载相同的模块组件和指令 ..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
在运行所有 spec.ts 文件并为每个 specs 注入(inject)各自的依赖项之前,是否有任何模式使其变得普遍,例如在开始时加载所有这些模块组件等。任何帮助都会很棒。
最佳答案
我的回答并不完整,如您所料。 但我希望它能对您有所帮助。
路由器 stub .ts
//----------Default Import------------
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
...snip...
export const test_imports = [
BrowserModule,
FormsModule,
HttpModule,
BrowserAnimationsModule
];
每个测试.spec.ts
import { test_imports } from '../testing/router-stubs';
..snip..
imports: [test_imports],
但提供者/声明不能以相同的方式使用。
关于unit-testing - TestBed configureTestingModule 在一个模块中定义所有 spec.ts 通用的导入、声明、提供程序和管道 - 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43319091/