Jest 是否支持 ES6 导入/导出? [英] Does Jest support ES6 import/export?
问题描述
如果我从 ES6 使用 import/export
那么我所有的 Jest 测试都会失败并显示错误:
If I use import/export
from ES6 then all my Jest tests fail with error:
意外的保留字
我将我的测试对象转换为使用旧式 IIFE 语法突然间我的测试通过了.或者,采用更简单的测试用例:
I convert my object under test to use old school IIFE syntax and suddenly my tests pass. Or, take an even simpler test case:
var Validation = require('../src/components/validation/validation'); // PASS
//import * as Validation from '../src/components/validation/validation' // FAIL
同样的错误.显然这里的导入/导出有问题.仅仅为了让我的测试框架满意而使用 ES5 语法重写我的代码对我来说是不切实际的.
Same error. Obviously there's a problem with import/export here. It's not practical for me to rewrite my code using ES5 syntax just to make my test framework happy.
我有 babel-jest.我尝试了来自 GitHub 问题的各种建议.到目前为止还不行.
I have babel-jest. I tried various suggestions from GitHub issues. It is no go so far.
"scripts": {
"start": "webpack-dev-server",
"test": "jest"
},
"jest": {
"testPathDirs": [
"__tests__"
],
"testPathIgnorePatterns": [
"/node_modules/"
],
"testFileExtensions": ["es6", "js"],
"moduleFileExtensions": ["js", "json", "es6"]
},
文件babelrc
{
"presets": ["es2015", "react"],
"plugins": ["transform-decorators-legacy"]
}
有没有办法解决这个问题?
Is there a fix for this?
推荐答案
UPDATE 2020 - ECMAScript 模块 (ESM) 的原生支持
根据这个问题,jest 有对 ESM 的原生支持@25.4.0
.这样你就不必再使用 babel 了.在撰写此答案时 (05/2020),要激活您需要做三件简单的事情:
UPDATE 2020 - native support of ECMAScript modules (ESM)
According to this issue, there is native support of ESM from jest@25.4.0
. So you won't have to use babel anymore. At the time of writing this answer (05/2020), to activate that you need to do three simple things:
- 确保您不会通过在配置文件中设置
transform: {}
来转换import
语句 - 运行
node@^12.16.0 ||>=13.2.0
带有--experimental-vm-modules
标志 - 使用
jest-environment-node
或jest-environment-jsdom-sixteen
运行您的测试.
- Make sure you don't transform away
import
statements by settingtransform: {}
in config file - Run
node@^12.16.0 || >=13.2.0
with--experimental-vm-modules
flag - Run your test with
jest-environment-node
orjest-environment-jsdom-sixteen
.
所以你的 Jest 配置文件应该至少包含以下内容:
So your Jest configuration file should contain at least this:
export default {
testEnvironment: 'jest-environment-node',
transform: {}
...
};
并且要设置 --experimental-vm-modules
标志,您必须按如下方式运行 Jest:
And to set --experimental-vm-modules
flag, you will have to run Jest as follows:
node --experimental-vm-modules node_modules/jest/bin/jest.js
另请注意,在 Github 问题中,此方法尚不支持 jest
对象.所以你可能需要手动导入:
Also note in the Github issue that this approach does not yet support the jest
object. So you may need to import it manually:
import {jest} from '@jest/globals'
(我希望这会在未来改变)
这篇关于Jest 是否支持 ES6 导入/导出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!