根底应用
- 装置jest
yarn add jest -D
- 配置package.json
{ "scripts": { "test": "jest" }, "devDependencies": { "jest": "^27.5.1" }}
- 测试代码
// sum.jsmodule.exports = function sum(a, b) { return a + b;};// sum.spec.jsconst sum = require("./sum");test("sum", () => { expect(sum(1, 1)).toBe(2);});
- 测试
yarn test
没有问题
配置反对esmodule
未做任何配置,间接将导入导出改为esmodule将会呈现这样的谬误
官网文档
只须要在package.json中一点配置即可反对esmodule
{ "license": "ISC", "type": "module", "scripts": { "test": "NODE_OPTIONS=--experimental-vm-modules jest" }, "devDependencies": { "jest": "^27.5.1" }}
容许测试胜利,不过会有一个提醒说VM Modules是一个试验个性
配置反对ts
除了jest须要装置@types/jest
ts-jest
typescript
这三个包
yarn add ts-jest @types/jest typescript -D
- 配置文件
jest.config.js
module.exports = { preset: "ts-jest", testEnvironment: "node",};
- 配置
tsconfig.json
没有esModuleInterop属性会又一些提醒,也能跑,package外面失常写"test": "jest"
就行
{ "compilerOptions": { "esModuleInterop": true }}
- 测试代码
// sum.tsexport function sum(a, b) { return a + b;}// sum.spec.tsimport { sum } from "./sum";describe("sum", () => { it("sum: 1+1=2", () => { expect(sum(1, 1)).toBe(2); });});
- 运行测试
yarn test
完满