vite中使用jest 踩坑⚠️

3,546 阅读1分钟

vite 中使用 jest

  • node 版本:v14.17.3
  • yarn :1.22.10
  • vite:2.5.20
  • 优先使用 yarn 安装依赖
  1. vite 创建项目

    npm init vite 
    # 选择 vue vue-ts 
    # 下载依赖 运行
    
  1. 新建 tests 文件夹

    // mkdir tests -> touch test.spec.ts import { add } from '../utils/tools'describe('1 + 1', () => {
      it('1 + 1 = 2', () => {
        expect(add(1,1)).toBe(2)
      })
    })
    
  1. 新建 utils

    // mkdir utils -> touch tools.tsfunction add(a: number, b: number): number{
      return a + b
    }
    ​
    export {
      add
    }
    
  1. 安装对应依赖

    # jest不支持esModule 需要安装 babel 解析
    yarn add @babel/core @babel/preset-env -D
    ​
    # 支持 ts 文件
    yarn add @babel/preset-typescript -D
    ​
    # babel-jest
    yarn add babel-jest -D
    ​
    # 安装 jest 相关依赖
    yarn add jest ts-jest vue-jest @types/jest @vue/test-utils -D
    # ts-jest ts文件 jest支持
    # vue-jest vue文件 支持
    # @types/jest 类型声明文件
    # @vue/test-utils
    
    yarn add babel-jest@26.0.0 jest@26.0.0 ts-jest@26.4.4 -D #固定版本
    
  1. package.json 配置

    {
      ...
      "scripts": {
        "test": "jest"
      },
      "jest": {
        "transform": {
          "^.+\.[t|j]sx?$": "babel-jest"
        }
      },
      ...
    }
    
  1. tsconfig.json

    {
      ...
       "types": ["vite/client", "jest"]
    }
    
  1. 新建 jest.config.js

    module.exports = {
      testMatch:[
          "**/?(*.)+(spec|test|unit).[jt]s?(x)" // 匹配测试文件
      ],
      transform: {
        "^.+\.[j|t]sx?$": "babel-jest",
        "^.+\.vue?$": "vue-jest",
        "^.+\.tsx$": "ts-jest"
      }
    }
    
  1. 新建 babel.config.json

    // ⚠️ 需要json 文件 js文件无法解决 esmodule 引入问题
    {
      "presets": [
        ["@babel/preset-env"],
        "@babel/preset-typescript"
      ]
    }
    

\