首页 > 解决方案 > Angular 7 业力测试与导入外部 JS 模块

问题描述

我正在测试一个 Angular 7 组件,该组件具有导入 JS 模块,例如:

组件.ts

import * as classA from '../../classA'; // Imported JS modules
export class component implements OnInit {
  public a = new classA(10); // Instantiate
  ...
}

类A.js

class classA {
  constructor (a) {
    this.max = a;
    ...
}

if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
    module.exports = classA;
}

组件.spec.ts

import * as classA from '../../classA';

我正在导入 classA,就像我在 component.ts 中所做的那样。

Component.ts 运行良好,但是当我运行 ng test 时,它给出了一个错误:TypeError: classA is not a constructor

我试图将它包含在 karma.conf.js 中,例如:

module.exports = function (config) {
  config.set({
    ...
    files: [
      "../app/classA.js"
    ]
  });
};

但仍然得到同样的错误。任何人都知道如何在单元测试中导入 JS 模块?

标签: javascriptangularkarma-jasminekarma-runnerangular7

解决方案


我找到了解决这个测试错误的方法。在 Angular 7 中,在 component.ts 中导入 JS commonjs 模块的正确方法是

import classA from '../../classA';

"esModuleInterop": true,
"allowSyntheticDefaultImports": true

在 tsconfig.json


推荐阅读