关于jest:初学jest如何配置支持esmodulets

6次阅读

共计 946 个字符,预计需要花费 3 分钟才能阅读完成。

根底应用

  • 装置 jest
yarn add jest -D
  • 配置 package.json
{
  "scripts": {"test": "jest"},
  "devDependencies": {"jest": "^27.5.1"}
}
  • 测试代码
// sum.js
module.exports = function sum(a, b) {return a + b;};

// sum.spec.js
const 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.ts
export function sum(a, b) {return a + b;}

// sum.spec.ts
import {sum} from "./sum";

describe("sum", () => {it("sum: 1+1=2", () => {expect(sum(1, 1)).toBe(2);
  });
});
  • 运行测试
yarn test

完满

正文完
 0