vite+vue3+ts工程如何快速添加jest单元测试?

1,281 阅读1分钟

前提是你已经应有了一套vite+vue3+ts工程脚手架

step1 安装依赖

# 安装 jest 相关依赖 这里以27版本为例,一定要安装指定版本影响到下面vue-jest依赖版本
npm i jest@27.0.5 ts-jest@27.0.4 @types/jest@26.0.0 -D
# ts-jest 是一个支持 `sourcemap` 的 TypeScript 预处理器,让你使用 TypeScript 编写 Jest 测试项目
# @types/jest 提供全局的类型声明文件不需要手动 import '@jest/globals'
# jest不支持esModule 需要安装对应 babel 解析
npm i @babel/core @babel/preset-env -D
# 添加babel支持 ts 文件
npm i @babel/preset-typescript -D
# babel-jest
npm i babel-jest@27.0.6 -D
npm i @vue/vue3-jest@27 @vue/test-utils -D
# @vue/vue3-jest@ vue文件 支持
# @vue/test-utils

注意:根据jest版本的不同 @vue/vue3-jest@27也需要安装不同的版本,具体参考官方指导:github.com/vuejs/vue-j…

step2 根目录新建 jest.config.js

module.exports = {
  testEnvironment: 'jsdom',
  testMatch:[
    "**/?(*.)+(spec|test|unit).[jt]s?(x)" // 匹配单元测试文件
  ],
  transform: {
    "^.+\.[j|t]sx?$": "babel-jest",
    "^.+\.vue?$": "@vue/vue3-jest",
    "^.+\.tsx$": "ts-jest"
  }
}

step3 修改 babel.config.js

module.exports = {
  presets: [
    ['@babel/preset-env', {
        targets: {
          node: 'current'
        }
      }
    ],
    "@babel/preset-typescript"
  ],
}

step4 修改 tsconfig.json 暂时没确定用处

{  
  ...   
  "types": ["vite/client", "jest"] 
}

step5 package.json 创建test命令

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

step6 根目录下创建 tests 文件夹 创建 test.spec.ts 进行测试

import { mount } from '@vue/test-utils'

// The component to test
const MessageComponent = {
  template: '<p>{{ msg }}</p>',
  props: ['msg']
}

test('displays message', () => {
  const wrapper = mount(MessageComponent, {
    props: {
      msg: 'Hello world'
    }
  })

  // Assert the rendered text of the component
  expect(wrapper.text()).toContain('Hello world')
})

step7 执行单元测试

npm run test

image.png

测试通过,打完收工!!!