配置Babel和Jest [英] Configuring Babel and Jest

查看:1003
本文介绍了配置Babel和Jest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TLDR:如何配置jest,使其使用babel编译测试文件,这些文件在globalSetupglobalTeardown中需要?

TLDR: How can I configure jest so that it uses babel to compile the test files and the files required in globalSetup and globalTeardown?

我一直在努力配置jestbabel.看来,当我运行测试时,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相同的配置时,可以运行测试.但是globalSetupglobalTeardown不能.

When I used an identical configuration with .babelrc instead, the tests could run. However the globalSetup and globalTeardown could not.

推荐答案

Jest当前不会转换globalSetupglobalTeardown中定义的模块. 此处.

Jest currently doesn't transform modules defined in globalSetup and globalTeardown. There's an open GitHub discussion here.

话虽这么说,但在同一线程上有一些解决方法.您必须在jest.config.js的顶部需要babel-registerbabel-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屋!

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