Testing ES6 class with Jest throws #39;not a constructor#39; error(使用Jest抛出而不是构造函数测试ES6类时出错)
本文介绍了使用Jest抛出而不是构造函数测试ES6类时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我发现了类似的问题here,但似乎没有答案。
我正在尝试使用Jest测试ES6类,如下所示:
// src/myclass.js
export default class MyClass {
constructor(options) {
// currently this is empty while I debug this problem
}
}
和测试:
// test/myclass.test.js
import { MyClass } from '../src/myclass.js';
describe("Test Constructor", () => {
test("doesn't throw error when constructed", async () => {
expect(() => {
const testMyClass = new MyClass();
}).not.toThrowError();
}
});
当我运行测试时,Jest抛出一个错误:
TypeError:_myClass.MyClass不是构造函数
我最好的猜测是这是Babel配置的问题,但我似乎无法解决这个问题。如果我将MyClass
更改为函数而不是类,并删除导出/导入(即类前的操作方式),则它会按预期工作。
以下是我在Package.json:
中的配置"devDependencies": {
"@babel/core": "^7.1.2",
"@babel/preset-env": "^7.1.0",
"babel-core": "^7.0.0-bridge.0",
"gulp": "^3.9.1",
"gulp-babel": "^8.0.0",
"gulp-jest": "^4.0.2",
"gulp-rename": "^1.4.0",
"gulp-uglify": "^3.0.1",
"jest": "^23.6.0",
"jest-cli": "^23.6.0",
"pump": "^3.0.0",
"regenerator-runtime": "^0.12.1"
},
"babel": {
"presets": [
"@babel/preset-env"
]
},
"jest": {
"testPathIgnorePatterns": [
"<rootDir>/node_modules/",
"<rootDir>/test/._*.test.js"
],
"testEnvironment": "jsdom",
"setupFiles": [
"<rootDir>/src/myclass.es6.js"
]
}
推荐答案
您的导入和导出语法不匹配。您需要更换其中一个,这样才能正常工作。如果要使用默认导出,例如:
export default class MyClass { ... }
则对应的导入为:
import MyClass from '../src/myclass.js'
或者如果您希望继续使用相同的导入语法,则在导出时删除"default":
export class MyClass { ... }
然后:
import { MyClass } from '../src/myclass.js'
这篇关于使用Jest抛出而不是构造函数测试ES6类时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:使用Jest抛出而不是构造函数测试ES6类时出错


基础教程推荐
猜你喜欢
- 在for循环中使用setTimeout 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 动态更新多个选择框 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 悬停时滑动输入并停留几秒钟 2022-01-01