Babel 在运行 Jest 时不会编译 .test.js 文件 [英] Babel will not compile .test.js files while running Jest
问题描述
在运行 yarn run jest --no-cache 时,会抛出一个错误:
While running yarn run jest --no-cache, An error is being thrown that says:
SyntaxError: Unexpected token import
我最好的猜测是 babel 没有到达这个测试文件.我需要将它们包含在 .babelrc 中吗?
My best guess is that babel is not reaching this this test file. Is their something special I need to include in .babelrc?
路径:
/src/tests/LandingPage.test.js
测试文件:
import React from 'react';
import ReactShallowRenderer from 'react-test-renderer/shallow';
import LandingPage from '../../components/LandingPage';
test('Should render LandingPage correctly', () => {
const renderer = new ReactShallowRenderer();
renderer.render(<LandingPage />);
expect(renderer.getRenderOutput()).toMatchSnapshot();
});
.babelrc :
{
"presets": [
"env",
"react"
],
"plugins": [
"transform-class-properties",
"transform-object-rest-spread"
]
}
推荐答案
感谢@hannad rehmann 在正确方向上的推动,这里是对我有用的解决方案.
Thanks @hannad rehmann for the nudge in the right direction here is the solution that worked for me.
yarn add babel-jest --dev
为测试环境配置 .babelrc
Jest 会自动将您的环境设置为测试,因此将您想要的任何配置复制到测试环境中.
Configure .babelrc for test env
Jest automatically sets your Env to test, so duplicate whatever config you want to the test env.
{
"presets": [
"env",
"react"
],
"plugins": [
"transform-class-properties",
"transform-object-rest-spread"
],
"env": {
"test": {
"presets": [
"env",
"react"
],
"plugins": [
"transform-class-properties",
"transform-object-rest-spread"
]
}
}
}
将 jest.config.json
添加到项目根目录
Add jest.config.json
to project root
{
"transform": {
"^.+\.jsx?$": "babel-jest"
}
}
最后,让你的测试脚本知道在哪里可以找到配置文件
我刚刚将它添加到 package.json 中的测试脚本中,但您也可以在命令行中运行它.
Finally, let your test script know where to find config file
I just added it to my test script in package.json, but you can also just run this in the command line.
"scripts": {
"test": "jest --config=jest.config.json --watch"
},
这篇关于Babel 在运行 Jest 时不会编译 .test.js 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!