前端基建-函数工具库之单元测试(2)

123 阅读1分钟

继之前的函数工具库,现在我们为函数工具库添加正则校验。

我是用的是jest

安装

 npm install --save-dev jest ts-jest @types/jest

配置 jest.config.js

 const config = {
  // A preset that is used as a base for Jest's configuration
  preset: 'ts-jest',
  // The test environment that will be used for testing
  testEnvironment: 'node',
  // The glob patterns Jest uses to detect test files
  testMatch: ['<rootDir>/tests/**/*.test.ts'], // 只运行 tests 目录下的测试文件
  // An array of file extensions your modules use
  moduleFileExtensions: ['ts', 'js', 'json'],
 }

配置 package.json

{
  "scripts": {
    "test": "jest",
  },
}

执行 npm run test

image.png

配置Husky提交代码前校验test

npm install husky --save-dev

添加hook

echo "npm test" > .husky/pre-commit

提交代码

image.png

可以看到运行了npm run test

lint-staged

如果只想针对修改的文件运行测试,可以安装 lint-staged

npm install lint-staged --save-dev

package.json 中添加:

"lint-staged": {
  "*.{js,ts,vue}": [
    "npm run test"
  ]
}

并修改 .husky/pre-commit

npx lint-staged

提交修改,如果修改的文件不包含单元测试,就不会执行npm run test

image.png

优化

配置eslint

先大概配置下,后期优化规则就行

npm install eslint -D  

image.png

eslint.config.mjs

import globals from "globals"
import pluginJs from "@eslint/js"
import tseslint from "typescript-eslint"

/** @type {import('eslint').Linter.Config[]} */
export default [
  { files: ["**/*.{js,mjs,cjs,ts}"] },
  { languageOptions: { globals: globals.browser } },
  pluginJs.configs.recommended,
  ...tseslint.configs.recommended,
  {
    rules: {
      "no-unused-vars": "warn", //  规则配置
      "no-undef": "warn",
      "@typescript-eslint/no-require-imports": "off",
    },
  },
]