Babel在运行Jest时不会编译.test.js文件 [英] Babel will not compile .test.js files while running Jest

查看:346
本文介绍了Babel在运行Jest时不会编译.test.js文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运行毛线时开玩笑-没有缓存,正在抛出一个错误,指出:

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自动将您的Env设置为测试环境,因此将您想要的任何配置复制到测试Env.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆