升级后将 Angular 10.2 与 Jest 一起使用时,ngx-quill 测试失败

ngx-quill tests fail when using Angular 10.2 with Jest after upgrade

从 Angular 9.x 升级到 Angular 10.x 所有使用 ngx-quill 组件 quill-editor 的组件规格无法加载.

这是由标准angular测试产生的:

    it('should create', () => {
        expect(component).toBeTruthy();
    });

这是他们产生的错误信息:

 FAIL   my-project  src/(...)/my-component.spec.ts
  ● Test suite failed to run

    Call retries were exceeded

      at ChildProcessWorker.initialize (node_modules/jest-worker/build/workers/ChildProcessWorker.js:193:21)

当我们的视图使用简单的 quill 编辑器时会发生这种情况:

<quill-editor formControlName="myControlName"></quill-editor>

(注释或删除此行允许测试通过)

之前通过 jest.mock 调用模拟模块 quill 就足够了:

jest.mock('quill');

但现在测试失败了...

我们在共享组件中加载 QuillModule 并根据需要导入此共享组件:

@NgModule({
    declarations: [],
    imports: [
        QuillModule.forRoot({
            modules: {
                toolbar: [
                    ['bold', 'italic', 'underline', 'strike'],
                ],
            },
        }),
    ],
    exports: [QuillModule],
})
export class QuillEditorModule {}

我们最终使用我们的包装器模块在所有规范文件中用笑话模拟模块 QuillEditorModule

确保它位于 ..spec.ts 文件的顶部,我们能够对 ngx-quill 模块及其使用的组件选择器“quill-editor”进行存根,并且所有测试再次通过:

import { QuillEditorModuleStub } from 'src/(my-app-paths)/quill-editor.module.stub';

jest.mock(`src/(my-app-paths)/quill-editor.module`, () => ({
    __esModule: true,
    QuillEditorModule: QuillEditorModuleStub,
}));

存根组件

import { Component, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

@Component({
    selector: 'quill-editor',
    template: '',
    providers: [
        {
            provide: NG_VALUE_ACCESSOR,
            useExisting: forwardRef(() => QuillEditorComponentStub),
            multi: true,
        },
    ],
})
export class QuillEditorComponentStub implements ControlValueAccessor {
    registerOnChange(fn: any): void {}

    registerOnTouched(fn: any): void {}

    writeValue(obj: any): void {}
}

存根模块:

import { NgModule } from '@angular/core';
import { QuillEditorComponentStub } from './quill-editor-component.stub';

@NgModule({
    declarations: [QuillEditorComponentStub],
    exports: [QuillEditorComponentStub],
})
export class QuillEditorModuleStub {}