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类时出错


猜你喜欢
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01