用jest做单元测试不得不知道的起手式配置,闭坑指南

做单元测试有很多的工具,今天在一个老项目中看到的用的工具是用的jest做的单元测试,特尝试更新下,遇到不少的问题。

相关依赖配置文件

在这里插入图片描述

npm install --save-dev jest
  • package.json
{
    
    
  "name": "jest-app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    
    
    "test": "jest"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    
    
    "@babel/core": "^7.26.0",
    "@babel/preset-env": "^7.26.0",
    "@babel/preset-typescript": "^7.26.0",
    "babel-jest": "^29.7.0",
    "jest": "^29.7.0",
    "jest-environment-jsdom": "^29.7.0",
    "ts-jest": "^29.2.5",
    "ts-node": "^10.9.2",
    "typescript": "^5.6.3"
  },
  "dependencies": {
    
    
    "tslib": "^2.8.0"
  }
}
  • tsconfig.json
{
    
    
  "compileOnSave": true,
  "compilerOptions": {
    
    
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "experimentalDecorators": true,
    "esModuleInterop": true,
    "importHelpers": true,
    "declaration": true,
    "outDir": "./dist",
    "sourceMap": true,
    "baseUrl": "./",
    "allowSyntheticDefaultImports": true,
    "paths": {
    
    
      "@/*": ["./src/*"],
      "tslib": ["node_modules/tslib/tslib.d.js"]
    },
    "target": "es5",
    "lib": ["DOM", "ESNext"]
  },
  "include": ["src/**/*"]
}

生成基础配置文件

npm init jest@latest
  • jest.config.js
module.exports = {
    
    
  preset: 'ts-jest',
  testEnvironment: 'node',
  transform: {
    
    
    '^.+\\.tsx?$': 'ts-jest',
    '^.+\\.jsx?$': 'babel-jest' // 使用 babel-jest 进行转换
  },
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node']
  // 添加其他 Jest 配置
}

使用 Babel

要使用esm语法,必须配置babel,否则会报错

  • babel.config.js
module.exports = {
    
    
  presets: [['@babel/preset-env', {
    
     targets: {
    
     node: 'current' } }]]
}

报错:This syntax requires an imported helper but module ‘tslib‘ cannot be found

解决方案如下:
1、安装tslib

npm install tslib

2、tsconfig.json中"compilerOptions"选项下新增“baseUrl”及“paths”配置

"baseUrl":".",
"paths": {
    
    
  "tslib" : ["node_modules/tslib/tslib.d.ts"]
}
  • .src/index.ts
export * from './array'
  • array.ts
export function sum(a: number, b: number): number {
    
    
  return a + b
}
  • 测试用例src/test/index.test.js,运行jest命令会自动搜索测试文件名xxx.test.js包含test的文件里面的内容
import {
    
     sum } from '../index'

test('adds 1 + 2 to equal 4 ', () => {
    
    
  expect(sum(1, 2)).toBe(4)
})

test('adds 1 + 2 to equal 3 ', () => {
    
    
  expect(sum(1, 2)).toBe(3)
})

逐个运行测试
请添加图片描述
一般都是命令行运行
请添加图片描述

附件

源码地址:https://gitee.com/motain/jest-app

猜你喜欢

转载自blog.csdn.net/qq_27702739/article/details/143376481