javascript - 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 模块?
解决方案
我找到了解决这个测试错误的方法。在 Angular 7 中,在 component.ts 中导入 JS commonjs 模块的正确方法是
import classA from '../../classA';
和
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
在 tsconfig.json
推荐阅读
- react-native - 错误'未定义不是对象'使用@react-navigation/drawer(检查文档和问题)
- c - (C) 程序完全忽略 scanf 和 fgets 函数
- html - SVG 错误:
属性 d:属性的意外结束 - php - Wordpress 无法通过 Ajax 插入/更新记录
- react-native - 如何在 React Native 中使用 NodeMediaClient 在 REAL 720 上进行流式传输?
- python - Fiona的Geopandas要求文件错误(错误:命令错误退出状态1:python setup.py egg_info)
- c++ - C ++在嵌套命名空间内定义外部命名空间的功能
- python - 训练数据集后无法绘制损失和准确性
- python - 每个元素沿一个轴的numpy数组位置
- react-native - 在 React Native 中从 API 获取数据