mengzhen
mengzhen

Reputation: 23

Angular 7 karma test with importing external JS modules

I am testing a Angular 7 component which has importing JS modules like:

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';

I am importing classA as what I did in component.ts.

Component.ts is working perfectly but when I am running ng test, it gives an error: TypeError: classA is not a constructor

I tried to include it in karma.conf.js like:

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?

Upvotes: 1

Views: 1246

Answers (2)

mengzhen
mengzhen

Reputation: 23

I found the way to fix this testing error. In Angular 7, the right way to import JS commonjs module in component.ts is

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

with

"esModuleInterop": true,
"allowSyntheticDefaultImports": true

in tsconfig.json

Upvotes: 1

Oleksandr Poshtaruk
Oleksandr Poshtaruk

Reputation: 2146

You use es6 modules import but define commonjs module. Better use es6 modules as well.

classA.js

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

Or use require:

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

Upvotes: 1

Related Questions