单测就这么简单-配置篇-react-monorepo

65 阅读1分钟

image.png

jest.config.mjs

// jest(jest.config.mjs)
import fs from 'node:fs'
//  typescript转js配置(采用swc包转)
const config = JSON.parse(fs.readFileSync(`${process.cwd()}/.swcrc`, 'utf-8'))

// 引入一份ts类型,对标typescript开发体验
/** @type {import('jest').Config} */
const jestConfig = {
  // 转译配置
  transform: {
    '^.+\\.(t|j)sx?$': ['@swc/jest', { ...config }],
  },
  extensionsToTreatAsEsm: ['.ts', '.tsx'],
  /**
   * 运行每个测试文件之前-执行这个路径里面的内容。
   * 这里用来配置@testing-library/jest-dom,
   * 并加载其api-typescript类型补充
   */
  setupFilesAfterEnv: ['<rootDir>/rules/setup-jest.ts'],
  /**
   * 单测里面,如需要使用到dom,这里需设置为jsdom
   */
  testEnvironment: 'jsdom',
}
export default jestConfig

tsconfig.json

{
  "compilerOptions": {
    "target": "ESNext",
    "lib": ["DOM", "DOM.Iterable", "ESNext"],
    "noEmitOnError": true,
    "allowJs": false,
    "noEmit": true,
    "skipLibCheck": true,
    "alwaysStrict": true,
    "strictNullChecks": true,
    "esModuleInterop": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "noImplicitAny": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "declaration": true,
    "noEmitHelpers": true,
    "preserveWatchOutput": true,
    "jsx": "react-jsx",
    "inlineSourceMap": true,
  }, 
  "include": [
    "./**/*.test.ts",
    "./**/*.test.tsx",
    "./**/test",
    "./rules/setup-jest.ts"
  ],
  "exclude": ["node_modules", "**/node_modules", "**/@types/"],
  // 重要的加速编译配置
  "references": [
    { "path": "./packages/form/tsconfig.json" },
    { "path": "./packages/utils/tsconfig.json" },
    { "path": "./packages/state/tsconfig.json" }
  ]
}

setup.jest.ts



### setup.jest.ts

```ts
import '@testing-library/jest-dom'
// 加载api-类型
import '@testing-library/jest-dom/jest-globals'

异常处理

类型“Matchers<void, HTMLElement> & SnapshotMatchers<void, HTMLElement> & Inverse<JestMatchers<void, HTMLElement>> & PromiseMatchers<...>”上不存在属性“toBeVisible”|“toBeDisable”。

在setup-jest.ts文件引入

import '@testing-library/jest-dom'
import '@testing-library/jest-dom/jest-globals'

jest.config.mjs setupFilesAfterEnv: ['<rootDir>/rules/setup-jest.ts'],

github.com/allroad8888…