初始化
mkdir leetcode && cd leetcode# 初始化cnpm init -y#依赖安装cnpm i jest @types/jest ts-jest typescript -D
目录结构
Package.js
{"name": "leetcode","version": "1.0.0","description": "","main": "index.js","scripts": {"test": "npx jest","coverage": "npx jest --coverage" // 生成测试报告},"keywords": [],"author": "","license": "ISC","devDependencies": {"@types/jest": "^26.0.22","jest": "^26.6.3","ts-jest": "^26.5.4","typescript": "^4.2.3"}}
jest.config.js
module.exports = {preset: 'ts-jest',testEnvironment: 'node',};
测试
源文件
// src/1/index.ts/*** @param {number[]} nums* @param {number} target* @return {number[]}*/function twoSum(nums: number[], target: number) {let map = new Map();for (let i = 0; i < nums.length; i++) {let temp = target - nums[i];if (map.has(temp)) {return [map.get(temp), i];} else {map.set(nums[i], i);}}return [];}export default twoSum;// src/1/index.spec.tsimport twoSum from "./index";describe.each([[[2, 7, 11, 15], 9, [0, 1]],[[3, 2, 4], 6, [1, 2]],[[3, 3], 6, [0, 1]],])("两数之和", (arr, target, expected) => {test(`${arr} + ${target} => ${expected}`, () => {expect(twoSum(arr, target)).toStrictEqual(expected);});});
jest
测试报告
测试报告文件
路径: coverage/lcov-report/index.html
