Migrating from jest to vitest

April 29, 2022

After migrating our build/dev tooling from vue-cli to vite I also migrated our unit testing framework at Lob from jest to vitest. The following are the steps I took.

NOTE: these instructions are specific to Vue 3

Install vitest

  1. install vitest library and dependencies

    npm install vitest jsdom c8 --save-dev
  2. add the following block to vite.config.js

    test: { environment: 'jsdom', globals: true, coverage: { include: ['src/**/*.{js,vue}'], exclude: [ 'src/**/index.js', // No need to cover index files for exports 'src/main.js', // No need to cover bootstrap file 'src/**/*.spec.js', // No need to cover test files 'src/**/*.stories.js', // No need to cover stories files 'src/theme/**', // No need to cover components just for showing theming 'src/components/Icons/**' // No need to cover components just for rendering svg icons ], branches: 80, functions: 80, lines: 80 } }
  3. add the following npm scripts to package.json

    "test": "vitest run", "test:watch": "vitest watch", "coverage": "vitest run --coverage",

Remove unneeded dependencies/config

  1. Uninstall jest related libraries

    npm uninstall babel-jest eslint-plugin-jest vue-jest --save-dev
  2. Remove jest.config

Update tests

  1. replace all jest object functions with vi (ex: replace jest.fn() with vi.fn())
  2. Some mocks that use a default export will need to be updated: https://vitest.dev/api/#vi-mock

Update eslint config

In .eslintrc or whatever your eslint config file is named:

  1. Add "vi": false to the globals section
  2. Remove from extends : plugin:jest/recommended

Resources

The following are some helpful resources I used when performing these migrations: