Angular Karma测试原型函数

Angular Karma testing prototype function

当我尝试 运行 ng 测试时,我得到一个错误

Property 'myFunction' does not exist on type 'FormArray'

它是 属性 添加到 app.module.ts 使其成为全球。

它是扩展 AbstractControl 添加 myFunction 的原型,因此可以在 AbstractControl 对象上调用它。 (完全像这里一样

我可以做些什么来让 Karma 承认它被正确使用或让它忽略它?

编辑: 完整错误:

ERROR in app/modules/settings/components/some-folder/some-folder2/some-folder3/some-folder4/myComponent.component.ts:74:23 - error TS2339: Property 'myFunction' does not exist on type 'FormArray'.

74 myFormArray.addValidators([MyValidator(someList)]);

当您 运行 进行测试时,app.module 不会隐式导入,因此您扩展原型的代码不是 运行。

所以你要么

  • 将整个 app.module 导入您的 TestBed.configureTestingModule,这不是一个好的做法,因为它会引入所有依赖项,
  • 或者创建一个测试模块,在其中 运行 原型扩展代码,并仅导入必要的依赖项(例如,表单模块(包含 FormArray)和一些组件或服务)
  • 或者只是 运行 beforeEach 中的原型扩展代码,所以当您的测试到达有表单的部分时,原型已经扩展了
beforeEach(() => {
    // just paste the prototype extending code here, something like the following
    AbstractControl.prototype.myFunction = () => {
        // ...
    }

    // or even better, if you extracted the function above to somewhere
    extendAbstractControl();
});`