Vite+Vue3+TypeScirpt搭建单元测试

2,777 阅读1分钟

Coding 完单元测试是必修之一,特别是写公共组件,毕竟谁也不想下次修改完心里没底是不。

Vue推荐的是 Vue Test Utilsjest 组合。在 Vue-Cli 下非常的简单,主要一句话:

vue add unit-jest

可是 Vite 中没有相应的用法,下面就手把手列出流程。

  1. 先在根目录写 jest.config.js
module.exports = {
  moduleFileExtensions: [
    'ts',
    'js',
    'jsx',
    'tsx',
    'json',
    // tell Jest to handle *.vue files
    'vue'
  ],
  transform: {
    // process *.vue files with vue-jest
    '^.+\\.vue$': require.resolve('vue-jest'),
    '^.+\\.tsx?$': require.resolve('ts-jest'),
    '.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$':
      require.resolve('jest-transform-stub'),
    '^.+\\.jsx?$': require.resolve('babel-jest')
  },
  transformIgnorePatterns: ['/node_modules/'],
  // support the same @ -> src alias mapping in source code
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1'
  },
  // testEnvironment: 'jest-environment-jsdom-fifteen',
  // serializer for snapshots
  snapshotSerializers: ['jest-serializer-vue'],
  testMatch: ['**/tests/unit/**/*.spec.[jt]s?(x)', '**/__tests__/*.[jt]s?(x)'],
  // https://github.com/facebook/jest/issues/6766
  testURL: 'http://localhost/'
}

如果你好奇哪来的,那就是 Vue-Cli的插件。以下摘取几个来解释下:

  • 这个配置比较全,连jsx也考虑到了
  • 里面那些用了 require.resolve 的,这些都需要去安装相应的依赖包的
  • moduleNameMapper 写别名,不认 tsconfig.jsonvite.config.js,得重新写
  • jest-serializer-vue 是弄快照的,快照真yyds,这也需要安装依赖包
  • testMatch抓取测试文件的规则,可以测试代码放到规则要求的地方或者改规则
  1. 安装 Vue Test Utils

由于我们是 Vue3,所以需要安装 next 版本

npm i -D @vue/test-utils@next
  1. 安装各种 jest相关的依赖包
npm i -D vue-jest@next

到写文章截止,vue-jest 的最新版不支持 jest>=27,全安装的26版本。

npm i -D jest@"<27" babel-jest@"<27" ts-jest@"<27" @types/jest@"<27"

还有两:

npm i -D jest-serializer-vue jest-transform-stub

还有这个,不安装 ts vue 里面的解构用法不好使:

npm i -D tslib
  1. 配置下 babel.config.js
module.exports = {
  ...
  env: {
    test: {
      presets: [
        [
          '@babel/preset-env',
          {
            modules: 'auto', // 需要babel来解析es module
            targets: {
              node: 'current' // 指定环境为当前node版本
            }
          }
        ]
      ]
    }
  }
}

如果没有安装 @babel/preset-env,补一下:

npm i -D @babel/preset-env
  1. 如果有 .eslintrc.js,需要在其中加入,不然测试代码会被各种提示:
module.exports = {
  ...
  overrides: [
    {
      files: [
        '**/__tests__/*.{j,t}s?(x)',
        '**/tests/unit/**/*.spec.{j,t}s?(x)'
      ],
      env: {
        jest: true
      }
    }
  ]
}
  1. 我们是用的TypeScirpt写的,需要在 tsconfig.json 加入:
{
  "compilerOptions": {
    ...
    "types": [..., "jest"] # 加入jest类型
  },
  "include": [
    ...
    "tests/**/*.ts", 
    "tests/**/*.tsx" # 把要测试文件地址也加入ts配置
  ]
}
  1. 最后,在 package.json 配置个script用于执行:
{
  ...
  "scripts": {
    "test:unit": "jest"
  },
  ...
}

到这里,我们的配置步骤就算完成了,下面以 Vue-Cli 自带的例子来测试下。

tests/unit/example.spec.js

import { shallowMount } from "@vue/test-utils";
import HelloWorld from "@/components/HelloWorld.vue";

describe("HelloWorld.vue", () => {
  it("renders props.msg when passed", () => {
    const msg = "new message";
    const wrapper = shallowMount(HelloWorld, {
      props: { msg },
    });
    expect(wrapper.text()).toMatch(msg);
  });
});

执行下:

npm run test:unit

image.png

Done.