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

根底应用

  • 装置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

完满

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理