簡體   English   中英

導入外部JS模塊進行Angular 7業力測試

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

我正在測試一個具有導入JS模塊的Angular 7組件,例如:

component.ts

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

classA.js

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

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

component.spec.ts

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

我要像在component.ts中一樣導入classA。

Component.ts正常運行,但是當我運行ng test時,出現錯誤: TypeError: classA is not a constructor

我試圖將其包含在karma.conf.js中,例如:

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

但是仍然出現相同的錯誤。 有誰知道如何在單元測試中導入JS模塊?

您使用es6模塊導入,但定義了commonjs模塊。 更好地使用es6模塊。

classA.js

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

或使用要求:

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

我找到了解決此測試錯誤的方法。 在Angular 7中,在component.ts中導入JS commonjs模塊的正確方法是

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

"esModuleInterop": true,
"allowSyntheticDefaultImports": true

在tsconfig.json中

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM