自定义节点环境中的意外令牌导入 [英] Unexpected token import in custom node environment
问题描述
使用扩展了NodeEnvironment
的自定义类时,我得到的是SyntaxError: Unexpected token import
.不使用自定义测试环境时,现代的JavaScript-ES模块等可以正常工作.
I am getting a SyntaxError: Unexpected token import
when using my custom class that extends NodeEnvironment
. When not using a custom test environment, modern JavaScript - ES modules, etc. works fine.
我正在使用节点8.11.1
和纱线1.6.0
.
I'm using node 8.11.1
and yarn 1.6.0
.
这是完整的错误:
$ jest --no-cache
FAIL __tests__/math.js
● Test suite failed to run
/home/user/workspace/web/jest-custom-environment-no-import/__tests__/_helpers_/environments/integration.js:1
(function (exports, require, module, __filename, __dirname) { import NodeEnvironment from 'jest-environment-node';
^^^^^^
SyntaxError: Unexpected token import
at node_modules/jest-runner/build/run_test.js:31:29
这是我的.babelrc
:
{
"presets": [
[
"@babel/preset-env",
{
"targets": {
"node": "current"
},
"shippedProposals": true
}
]
]
}
还有我的package.json
的jest
部分:
"jest": {
"testEnvironment": "./__tests__/_helpers_/environments/integration.js",
"testPathIgnorePatterns": ["/node_modules/", "/_helpers_/"],
"verbose": true
}
自定义环境:
import NodeEnvironment from 'jest-environment-node';
export default class IntegrationEnvironment extends NodeEnvironment {
async setup() {
await super.setup();
}
async teardown() {
await super.teardown();
}
runScript(script) {
return super.runScript(script);
}
}
我还创建了一个 GitHub存储库,演示了这个问题.
I've also created a GitHub repo that demonstrates this issue.
推荐答案
我使用 esm创建了一个明智的解决方法.我创建了一个加载esm的附加文件,该文件加载了我的自定义Jest环境.
I created a sensible workaround using esm. I created an additional file that loads esm, which loads my custom Jest environment.
我的package.json
现在包含:
"jest": {
"testEnvironment": "./__tests__/_helpers_/environments/integration.index.js",
"testPathIgnorePatterns": ["/node_modules/", "/_helpers_/"],
"verbose": true
}
文件./__tests__/_helpers_/environments/integration.index.js
包含:
// eslint-disable-next-line no-global-assign
require = require('esm')(module);
module.exports = require('./integration').default;
./__tests__/_helpers_/environments/integration.js
保持不变.
在 esm分支中找到了一个工作示例是我的原始存储库.
这篇关于自定义节点环境中的意外令牌导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!