安装单元测试依赖 - jest
运行如下命令:安装依赖
yarn global add jest
// or
yarn add --dev jest
更多可参考文章:如何在项目中安装使用jest
当我们想用es6提供的import来导入模块或者想要async的时候,就需要用babel转换
安装babel-loader相关依赖
运行如下命令:安装依赖
yarn add --dev babel-loader @babel/core @babel/preset-env regenerator-runtime
依赖名称 | 描述 |
---|---|
babel-loader | 此 package 允许你使用 Babel 和 webpack 转译 JavaScript 文件 |
@babel/core | 所有的转译都将使用本地配置文件( .babelrc 或者 package.json ) |
@babel/preset-env | 编译最新版本JavaScript |
regenerator-runtime | Standalone runtime for Regenerator-compiled generator and async functions |
在webpack.config.js中添加babel-loader
webpack.config.js
const path = require("path");
module.exports = {
...
module: {
rules: [
// add the following:
{
test: /(\.jsx|\.js)$/,
use: {
loader: "babel-loader",
// 如果在这里配置options,有可能jest中无法识别到babel的配置
// 我遇到了上述情况,把options移到.babelrc中即可解决
// options: {
// presets: presets: ["@babel/preset-env", "@babel/preset-react"]
// }
},
exclude: /node_modules/
},
...
]
},
...
};
在.babelrc中配置babel
在package.json所在的根目录下创建 .babelrc,然后把下面的代码复制进去
{
"presets": [
[
"@babel/preset-env",
{
"targets": {
"node": "current" // 根据当前节点版本进行编译
}
}
],
]
}
Done
在项目中你喜欢的任意路径下,创建sum.js和sum.test.js
sum.js
function sum (a, b) {
return a + b;
}
module.exports = sum;
sum.test.js
const sum = require('../sum');
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
如果你是全局安装的话,运行如下命令进行测试:
jest
即可看到刚才的测试用例通过: