简体   繁体   English

导入外部JS模块进行Angular 7业力测试

[英]Angular 7 karma test with importing external JS modules

I am testing a Angular 7 component which has importing JS modules like: 我正在测试一个具有导入JS模块的Angular 7组件,例如:

component.ts component.ts

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

classA.js classA.js

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

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

component.spec.ts component.spec.ts

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

I am importing classA as what I did in component.ts. 我要像在component.ts中一样导入classA。

Component.ts is working perfectly but when I am running ng test, it gives an error: TypeError: classA is not a constructor Component.ts正常运行,但是当我运行ng test时,出现错误: TypeError: classA is not a constructor

I tried to include it in karma.conf.js like: 我试图将其包含在karma.conf.js中,例如:

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

But still get same error. 但是仍然出现相同的错误。 Anyone has any idea how to import JS modules in unit testing? 有谁知道如何在单元测试中导入JS模块?

You use es6 modules import but define commonjs module. 您使用es6模块导入,但定义了commonjs模块。 Better use es6 modules as well. 更好地使用es6模块。

classA.js classA.js

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

Or use require: 或使用要求:

 let classA = require('../../classA');

I found the way to fix this testing error. 我找到了解决此测试错误的方法。 In Angular 7, the right way to import JS commonjs module in component.ts is 在Angular 7中,在component.ts中导入JS commonjs模块的正确方法是

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

with

"esModuleInterop": true,
"allowSyntheticDefaultImports": true

in tsconfig.json 在tsconfig.json中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM