How to Setup Vue Test Utils for Vue2 Application

How to Setup Vue Test Utils for Vue2 Application

I was working on the vue2 app and wanted to set up a unit test. Since vue3 is now available, and their testing libraries have also been updated to support vue3, Because of versioning, I had difficulty configuring vue2 with test-utils. That is why I am writing this guide to assist others who have similar goals.

In this guide, I've compiled all of the libraries and their versions, as well as all of the configuration needed to run the unit test. However, we will not cover how to write test cases; don't worry, I will provide a GitHub repo with test cases.

Dependencies

In the following table, I have listed all the required libraries we need to install. so make sure you install them first as dev dependencies.

Assuming you have set up the vue2 application.

Package nameDescription
npm i -D @vue/test-utils@1vue test-utils library to test vue2 component. (version is important)
npm i -D @vue/vue2-jestJest transformer for Vue Single File Components.
npm i -D jestmost popular JavaScript testing library
npm i -D jest-environment-jsdomBrowser DOM Enviroment
npm i -D babel-jest @babel/core @babel/preset-env babel-core@^7.0.0-bridge.0To support latest javascript features in our test files

Configurations

Babel Configuration

create babel.config.json and paste the following code.

{
  "presets": ["@babel/preset-env"]
}

Jest Configuration

create jest.config.js and paste the following code

module.exports = {
  verbose: true,
  testEnvironment: 'jsdom',
  moduleFileExtensions: [ 'js', 'json', 'vue' ],
  moduleDirectories: [ 'node_modules', '<rootDir>' ],
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/$1', // resolves the `@/components` path
  },
  transform: {
    '^.+\\.js$': 'babel-jest', // test .js files with babel-jest
    '^.+\\.vue$': '@vue/vue2-jest', // test .vue files with vue2-jest
  },
};

package.json

Add the script in package.json to run the test

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

We are ready to write the test.

You can find all of the configurations with test examples in the chouglesaud/vue2-test-util repository.

Thanks for reading, I hope it was helpful. If you run across any setup problems, please comment or open an issue on Github.

Helpful References

Did you find this article valuable?

Support saud chougle by becoming a sponsor. Any amount is appreciated!