基本环境
安装依赖
npm install -D jest babel-jest babel-core babel-preset-env regenerator-runtime
备注:安装babel 为了让jest 支持ES6语法 import/export
package.json
{ "type": "module", "scripts": { "test": "jest --verbose" }, "devDependencies": { "babel-core": "^6.26.3", "babel-jest": "^28.1.3", "babel-preset-env": "^1.7.0", "jest": "^28.1.3", "regenerator-runtime": "^0.13.9" } }
babel 配置文件 .babelrc
{ "presets": ["env"] }
测试示例
src/functions.js
export default { sum(a, b) { return a + b }, }
tests/functions.test.js
import functions from '../src/functions' test('sum(2 + 2) 等于 4', () => { expect(functions.sum(2, 2)).toBe(4) })
运行测试
$ npx jest PASS tests/functions.test.js ✓ sum(2 + 2) 等于 4 (1 ms) Test Suites: 1 passed, 1 total Tests: 1 passed, 1 total Snapshots: 0 total Time: 1.141 s Ran all test suites.