首页 > 解决方案 > Angular Karma 测试原型功能

问题描述

当我尝试运行 ng test 时,我收到一个错误

类型“FormArray”上不存在属性“myFunction”

它是一个添加到 app.module.ts 以使其全局化的属性。

它是扩展 AbstractControl 添加 myFunction 的原型,因此可以在 AbstractControl 对象上调用它。(完全像这里https://stackoverflow.com/a/47065916一样)

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

编辑:完全错误:

app/modules/settings/components/some-folder/some-folder2/some-folder3/some-folder4/myComponent.component.ts:74:23 中的错误 - 错误 TS2339:属性 'myFunction' 在类型'FormArray 上不存在'。

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

标签: angulartestingkarma-jasmine

解决方案


当您运行测试时,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();
});`

推荐阅读