问题
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.
I'm using node 8.11.1
and yarn 1.6.0
.
This is the full error:
$ 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
This is my .babelrc
:
{
"presets": [
[
"@babel/preset-env",
{
"targets": {
"node": "current"
},
"shippedProposals": true
}
]
]
}
And the jest
portion of my package.json
:
"jest": {
"testEnvironment": "./__tests__/_helpers_/environments/integration.js",
"testPathIgnorePatterns": ["/node_modules/", "/_helpers_/"],
"verbose": true
}
The custom environment:
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);
}
}
I've also created a GitHub repo that demonstrates this issue.
回答1:
I created a sensible workaround using esm. I created an additional file that loads esm, which loads my custom Jest environment.
My package.json
now contains:
"jest": {
"testEnvironment": "./__tests__/_helpers_/environments/integration.index.js",
"testPathIgnorePatterns": ["/node_modules/", "/_helpers_/"],
"verbose": true
}
The file ./__tests__/_helpers_/environments/integration.index.js
contains:
// eslint-disable-next-line no-global-assign
require = require('esm')(module);
module.exports = require('./integration').default;
./__tests__/_helpers_/environments/integration.js
remains unchanged.
A working example is found in the esm branch of my original repo.
来源:https://stackoverflow.com/questions/49930302/unexpected-token-import-in-custom-node-environment