首页 > 解决方案 > Jasmine 编译/创建与 beforeAll/beforeEach 奇怪的组件

问题描述

我正在为我的应用程序编写一些单元测试,我遇到了一个非常奇怪的情况。我构建了一个有角度的应用程序,我正在使用 karma&jasmine 进行单元/集成测试。

这是交易:我写了这段代码

describe("Body Container component", () => {
    let component: BodyContainerComponent;
    let fixture: ComponentFixture<BodyContainerComponent>;
    beforeEach(async () => {
        getTestBed().configureTestingModule({
            imports: [AppTestingModule]
        });
        await getTestBed().compileComponents();
        fixture = getTestBed().createComponent(BodyContainerComponent);
        component = fixture.componentInstance;
        component.ngOnInit();
        fixture.detectChanges();
    });

它工作正常,测试被正确编译和执行(并通过)。不过,我想它们确实需要一段时间,因为每次 testingModule 都会重新配置并编译组件。

所以a试图以这种方式改变它:

 beforeAll(async () => {
    getTestBed().resetTestingModule();
    getTestBed().configureTestingModule({
        imports: [AppTestingModule]
    });
    await getTestBed().compileComponents();
});

beforeEach(async () => {
    fixture = getTestBed().createComponent(BodyContainerComponent);
    component = fixture.componentInstance;
    component.ngOnInit();
    fixture.detectChanges();
});

尽管在 getTestBed().createComponent 上调用的相同逻辑/API 的此版本失败,但失败并显示:

 Error: Illegal state: Could not load the summary for directive BodyContainerComponent.
    error properties: Object({ ngSyntaxError: true })
        at syntaxError (http://localhost:9876/node_modules/@angular/compiler/fesm5/compiler.js?:2430:1)
        at CompileMetadataResolver.push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver.getDirectiveSummary (http://localhost:9876/node_modules/@angular/compiler/fesm5/compiler.js?:18535:1)
        at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler.getComponentFactory (http://localhost:9876/node_modules/@angular/compiler/fesm5/compiler.js?:25979:1)
        at CompilerImpl.push../node_modules/@angular/platform-browser-dynamic/fesm5/platform-browser-dynamic.js.CompilerImpl.getComponentFactory (http://localhost:9876/node_modules/@angular/platform-browser-dynamic/fesm5/platform-browser-dynamic.js?:162:1)
        at TestingCompilerImpl.push../node_modules/@angular/platform-browser-dynamic/fesm5/testing.js.TestingCompilerImpl.getComponentFactory (http://localhost:9876/node_modules/@angular/platform-browser-dynamic/fesm5/testing.js?:110:1)
        at TestBedViewEngine.push../node_modules/@angular/core/fesm5/testing.js.TestBedViewEngine.createComponent (http://localhost:9876/node_modules/@angular/core/fesm5/testing.js?:1905:1)
        at Object.<anonymous> (http://localhost:9876/src/test/integration/app/components/body-container.integration-spec.ts?:21:32)
        at step (http://localhost:9876/node_modules/tslib/tslib.es6.js?:97:1)
        at Object.next (http://localhost:9876/node_modules/tslib/tslib.es6.js?:78:45)
        at http://localhost:9876/node_modules/tslib/tslib.es6.js?:71:1

我尝试了各种迭代和更改以使其正常工作,但错误仍然存​​在。经过一些分析,我可以说: 1- async/await 工作正常,只有在 beforeAll 完成后才调用 beforeach 2- 每个测试都会给出上面的错误,即使是第一个(这很奇怪,因为从逻辑上讲,第一个不应该改变两个版本之间的英寸

我注意到的一件事是第一个版本的测试是随机执行的,而第二个版本似乎是按照顺序执行的。第二个版本之前的异步并没有改变任何东西,我也尝试调用各种重置/销毁方法,但似乎没有任何贡献。

你知道为什么会这样吗?解决不了也没关系,毕竟是看整个构建过程的小优化,我比较好奇为什么会这样。

编辑:在附加分析之后,通过查看 testBed 实例,我注意到“beforeEach only”实现有

TestBedViewEngine{_instantiated: false, _compiler: TestingCompilerImpl{_compiler: CompilerImpl{_metadataResolver: ..., _delegate: ..., injector: ...}, _directiveResolver: MockDirectiveResolver{_reflector: ..., _directives: ...}, _pipeResolver: MockPipeResolver{_reflector: ..., _pipes: ...}, _moduleResolver: MockNgModuleResolver{_reflector: ..., _ngModules: ...}, _overrider: MetadataOverrider{_references: ...}}, _moduleRef: null, _moduleFactory: NgModuleFactory_{moduleType: function DynamicTestModule() { ... }, _bootstrapComponents: [], _ngModuleDefFactory: function(_l) { ... }}, _compilerOptions: [], _moduleOverrides: [], _componentOverrides: [], _directiveOverrides: [], _pipeOverrides: [], _providers: [], _declarations: [], _imports: [function AppTestingModule() { ... }], _schemas: [], _activeFixtures: [], _testEnvAotSummaries: function () { ... }, _aotSummaries: [], _templateOverrides: [], _isRoot: true, _rootProviderOverrides: [], platform: PlatformRef{_injector: StaticInjector{parent: ..., source: ..., _records: ...}, _modules: [], _destroyListeners: [], _destroyed: false}, ngModule: function BrowserDynamicTestingModule() { ... }}

而 beforeAll 有:

TestBedViewEngine{_instantiated: false, _compiler: null, _moduleRef: null, _moduleFactory: null, _compilerOptions: [], _moduleOverrides: [], _componentOverrides: [], _directiveOverrides: [], _pipeOverrides: [], _providers: [], _declarations: [], _imports: [], _schemas: [], _activeFixtures: [], _testEnvAotSummaries: function () { ... }, _aotSummaries: [], _templateOverrides: [], _isRoot: true, _rootProviderOverrides: [], platform: PlatformRef{_injector: StaticInjector{parent: ..., source: ..., _records: ...}, _modules: [], _destroyListeners: [], _destroyed: false}, ngModule: function BrowserDynamicTestingModule() { ... }}

我可以通过这个输出看到的最大区别是_compiler,它分别为空和实例化。此 TestBed“快照”是在 createComponent 调用之前拍摄的

标签: angularjasminekarma-runner

解决方案


我实际上发现问题可以在这里找到https://github.com/angular/angular/issues/12409

基本上,总结一下,angular 实际上重新定义了 beforeEach 函数,添加了一些非常自以为是的行为。具体来说,它写在这里:https ://github.com/angular/angular/blob/master/packages/core/testing/src/before_each.ts#L24

出于这个原因,在 beforeAll 中配置的测试模块实际上在 beforeEach 中重置(在 createComponent 调用之前)。而是仅使用 beforeEach 实际上有效,因为模块是在重置调用之后配置的。

因此,您要么按照预期使用 beforeEach ,牺牲速度(角度观点是每次测试时提供的服务都应该是新鲜的,这对于无状态的东西没有意义),或者您可以选择 2 种不同的解决方案:1)再次重新定义全局beforeEach,将其恢复为默认值,然后放回 Angular 行为:这当然是一种 hack,并且非常不稳定并且会引发随机错误,因为 Angular 假定模块对于它自己的内部来说是新鲜的 2)根本不要使用 beforeEach,配置模块在 beforeAll 中,然后将所有 beforeEach 活动请求到您在每个 it 语句上调用的自定义函数


推荐阅读