初学jest,如何配置支持esmodule、ts

发布于:2023-03-12 ⋅ 阅读:(328) ⋅ 点赞:(0)

基础使用

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

没有问题

image.png

配置支持esmodule

未做任何配置,直接将导入导出改为esmodule将会出现这样的错误

image.png

官方文档

只需要在package.json中一点配置即可支持esmodule

{
  "license": "ISC",
  "type": "module",
  "scripts": {
    "test": "NODE_OPTIONS=--experimental-vm-modules jest"
  },
  "devDependencies": {
    "jest": "^27.5.1"
  }
}

允许测试成功,不过会有一个提示说VM Modules是一个实验特性

image.png

配置支持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

完美

image.png

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到