文章目录
- 前言
- 安装
- 配置
- .vscode/launch.json
- jest.config.ts
- ts.config.ts
- 测试例子
前言
简单记录一下vscode里跑Jest单元测试。
安装
yarn add -D ts-jest ts-node @types/jest jest
配置
.vscode/launch.json
{"version": "0.2.0","configurations": [{"type": "node","request": "launch","name": "Jest single run all tests","program": "${workspaceRoot}/node_modules/jest/bin/jest.js","args": ["-c","./jest.config.ts","--verbose","-i","--no-cache"],"console": "integratedTerminal","internalConsoleOptions": "neverOpen"}]}
jest.config.ts
import type { Config } from 'jest';const config: Config = {verbose: true,preset: "ts-jest",transform: { "^.+\\.ts?$": "ts-jest" },moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
};export default config;
ts.config.ts
{"compilerOptions": {"target": "es5","lib": ["dom", "dom.iterable", "esnext"],"allowJs": true,"skipLibCheck": true,"strict": true,"noEmit": true,"esModuleInterop": true,"module": "esnext","moduleResolution": "bundler","resolveJsonModule": true,"isolatedModules": true,"jsx": "preserve","incremental": true,"types": ["jest","node"],"plugins": [{"name": "next"}],"paths": {"@/*": ["./src/*"]}},"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", "tests/**/*"],"exclude": ["node_modules"]
}
测试例子
import dayjs from 'dayjs';
import { describe } from 'node:test';
dayjs.locale('zh-cn') // 全局使用简体中文import add from './add';describe('add', () => {it('should return the sum of two numbers', () => {expect(add(1, 2)).toBe(3);});it('should return the sum of zero numbers', () => {expect(add(0, 0)).toBe(0);});it('should return the sum of negative numbers', () => {expect(add(-1, -2)).toBe(-3);});
});describe('正则表达式测试', () => {it('should get the host name', () => {const str = 'www.baidu.com';const regex = /www\.(.*)\.(com|cn|org)/;const result = str.match(regex);console.log(result)if(result) {console.log(result[1])expect(result[1]).toBe('baidu')} });})