配置Babel和Jest [英] Configuring Babel and Jest
问题描述
TLDR:如何配置jest
,使其使用babel
编译测试文件和,这些文件在globalSetup
和globalTeardown
中需要?
TLDR: How can I configure jest
so that it uses babel
to compile the test files and the files required in globalSetup
and globalTeardown
?
我一直在努力配置jest
和babel
.看来,当我运行测试时,babel
无法加载配置文件,或者根本没有运行.
I've been struggling a lot to configure jest
and babel
. It seems that when I run my tests babel
fails to load the configuration file, or perhaps it doesn't run at all.
在中 package.json:
in package.json:
{
"scripts": {
"start": "babel-node src/index.js",
"test": "jest src/tests/*.test.js",
},
"devDependencies": {
"@babel/cli": "^7.0.0-rc.1",
"@babel/core": "^7.0.0-rc.1",
"@babel/node": "^7.0.0-rc.1",
"@babel/preset-env": "^7.0.0-rc.1",
"babel-jest": "^23.4.2",
"jest": "^23.5.0",
}
}
在中 babel.config.js:
in babel.config.js:
module.exports = (api) => {
if (api) api.cache(true);
const presets = ['@babel/preset-env'];
const plugins = [];
return {
presets,
plugins,
};
};
在中 jest.config.js:
in jest.config.js:
module.exports = {
globalSetup: './src/config/jest/setup',
globalTeardown: './src/config/jest/teardown',
};
当我运行npm run test
时,出现以下错误:
When I run npm run test
I get the following error:
import app from '../../index';
^^^^^^ SyntaxError: Unexpected token import
...我认为这意味着babel
无法正确配置.我尝试登录配置文件,并且babel.config.js
仅在执行npm start
时运行.
...which I assume means that babel
failed to configure properly. I tried logging on both config files and babel.config.js
is only run when I do npm start
.
当我使用与.babelrc
相同的配置时,可以运行测试.但是globalSetup
和globalTeardown
不能.
When I used an identical configuration with .babelrc
instead, the tests could run. However the globalSetup
and globalTeardown
could not.
推荐答案
Jest当前不会转换globalSetup
和globalTeardown
中定义的模块. 此处.
Jest currently doesn't transform modules defined in globalSetup
and globalTeardown
. There's an open GitHub discussion here.
话虽这么说,但在同一线程上有一些解决方法.您必须在jest.config.js
的顶部需要babel-register
和babel-polyfill
.这是完整的实现: https://github.com/facebook/jest/issues/5164#issuecomment-366139663
That being said, there are some workarounds on the same thread. You'll have to require babel-register
and babel-polyfill
on top of your jest.config.js
. Here is the full implementation: https://github.com/facebook/jest/issues/5164#issuecomment-366139663
如果有人正在使用需要ts-node/register
的TypeScript,则应使其正常工作. https://github.com/facebook/jest/issues/5164#issuecomment- 376006851
If someone is using TypeScript requiring ts-node/register
should make it work. https://github.com/facebook/jest/issues/5164#issuecomment-376006851
这篇关于配置Babel和Jest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!