使用 Jest 测试 ES6 模块 [英] Test ES6 modules with Jest

查看:33
本文介绍了使用 Jest 测试 ES6 模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 Jest 测试 ES6 模块.

How to test ES6 modules with Jest.

示例:

sum.js

const sum = function (a, b) {
  return a + b;
}

export default sum;

sum.test.js

import sum from './sum';

test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);
});

推荐答案

唯一的要求是将你的 test 环境配置为 Babel,并添加 es2015 转换插件:

The only requirement is to config your test environment to Babel, and add the es2015 transform plugin:

第 1 步:

将您的 test 环境添加到项目根目录中的 .babelrc 中:

Add your test environment to .babelrc in the root of your project:

{
  "env": {
    "test": {
      "plugins": ["@babel/plugin-transform-modules-commonjs"]
    }
  }
}

第 2 步:

安装es2015转换插件:

Install the es2015 transform plugin:

npm install --save-dev @babel/plugin-transform-modules-commonjs

<小时>

就是这样. Jest 将自动启用从 ES 模块到 CommonJS 的编译,而无需为 package.json<中的 jest 属性通知其他选项/代码>.


And that's it. Jest will enable compilation from ES modules to CommonJS automatically, without having to inform additional options to your jest property inside package.json.

这篇关于使用 Jest 测试 ES6 模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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