Vite+Vue3+TypeScript 使用 jest(后期添加)

1,119 阅读1分钟

1 版本

  • node: >12.0.0 注意: 12.4.0会出现问题:Cannot find module '@babel/traverse'
  • 推荐使用yarn安装 Vue3依赖官方推荐用yarn安装

2 新建 tests 文件夹

3 test下面新建 units

4 安装对应依赖

# 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 jest ts-jest -D #

5 package.json 配置

{
  ...
  "scripts": {
    "test": "jest"
  },
  "jest": {
    "verbose": true,
    "moduleNameMapper": {
      "^@/(.*)$": "<rootDir>/src/$1"
    },
    "moduleFileExtensions": [
      "js",
      "vue",
      "ts"
    ],
    "transformIgnorePatterns": [
      "/node_modules/"
    ],
    "transform": {
      "^.+\\.[j|t]sx?$": "babel-jest",
      "^.+\\.vue?$": "vue-jest",
      "^.+\\.tsx$": "ts-jest"
    },
    "testMatch": [
      "**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)"
    ],
    "testResultsProcessor": "./node_modules/jest-html-reporter"
  },
  ...
}

6 新建 babel.config.json

// 'presets' :⚠️ 需要json 文件 js文件无法解决 esmodule 引入问题  
// 'plugins' :⚠️ 配置 转换ES7的 async/await语法
{
  "presets": [
    ["@babel/preset-env"],
    "@babel/preset-typescript"
  ],
  "plugins": ["@babel/plugin-transform-runtime"]
}