ITZone

Some tips for writing unit testing Vue Components with Jest

Using Jest to test Vue.js components can be quite difficult. We need a separate Vue Test Utils package ( @vue/test-utils ) to virtually mount our components and use Jest to run the tests. Because these two libraries work together, it is important to ensure that we do not get confused about which library’s API calls. Along with these libraries, we need to pay attention to the specific methods of JSDOM (virtual browser environment), which comes with Jest. These can be confusing and may prevent us from writing unittest.

For example, shallowMount() is a method of Vue Test Utils to create a shallow wrapper component (using shallow rendering to avoid rendering children components) and beforeEach() is a method of Jest that implements callback arguments before each test. We run shallowMount() inside beforeEach() so that a component is mounted before each test.
I made a list of the common test methods my team used to help write our unit Vue components successfully. Hope this helps others go through the same process.

Initial Setup

Get started by setting up Jest. Install Jest npm package devDependencies

Now, install the Vue Test Utils application and other dependencies like babel-jest , vue-jest , etc. (taken from the Vue Test Utils docs)

Once we have all the packages jest.config.js , let’s create a jest config file named jest.config.js in the root of our project. As an alternative, we can also add the JSON object inside module.exports to the jest: {} attribute to package.json to cut down the number of configuration files we have to manage.

Share the news now