Quick Summary:

In this tutorial, we are going to learn how to use Jest Vue Test Utils with Vue3 at the beginner level. Before we start, here are the basics.

Table of Contents

What are Vue Test Utils?

Vue Test Utils is the unit testing utility library for Vue.js, which contains sets of utility functions aimed to simplify testing Vue. js components. It provides us helper methods for vue js to interact with vue js component.

What is Vue Jest?

Jest is a JavaScript unit testing framework created by facebook which includes a lot of features like snapshot testing, code coverage, etc.

Getting Started With Vue Testing Utils

First, we will create our vue project using Vue cli.

Copy Text
vue create <name-of-project>

It will prompt three options; go ahead and select this one: Manually select features.

Copy Text
? Please pick a preset: (Use arrow keys)
> Default ([Vue 3] babel, eslint)       
  Default ([Vue 2] babel, eslint)       
  Manually select features

We will add Unit Testing feature using space key, after which we will press enter key.

Copy Text
? Please pick a preset: Manually select features
? Check the features needed for your project: (Press <space> to select, <a> to toggle all, <i> to invert selection, and <enter> to 
proceed)
>(*) Babel
 ( ) TypeScript
 ( ) Progressive Web App (PWA) Support
 ( ) Router
 ( ) Vuex
 ( ) CSS Pre-processors
 (*) Linter / Formatter
 ( ) Unit Testing
 ( ) E2E Testing

Other features can be added as required, but we will be using only Unit Testing for this tutorial. So unselect Linter / Formatter or select ESLint with error prevention only.

After proceeding, we will be required to choose the version of Vue, select 3.x.

Copy Text
? Check the features needed for your project: Babel, Unit
? Choose a version of Vue.js that you want to start the project with (Use arrow keys)
> 3.x
  2.x

Choose jest as the next option shows using the arrow keys.

Copy Text
? Choose a version of Vue.js that you want to start the project with 3.x
? Pick a unit testing solution: (Use arrow keys)
> Jest
  Mocha + Chai

Thereafter, you will see options to place the config, where you should select: In dedicated config files, and proceed.

Copy Text
? Where do you prefer placing config for Babel, ESLint, etc.? (Use arrow keys)
> In dedicated config files
  In package.json

In the final question, type N, and hit enter. Now your project will be created by Vue CLI, and the folder structure will look something like this:

Folder Structure

Cd to vue project created to change directory, open it in your favorite editor.

Want to build highly customized web interfaces with the help of the Vue.js framework?
Bacancy is here for you! Contact us now and hire vue js developer from us to build performance-driven User Interface

How to Write Unit Test with Jest Vue Test Utils?

In this section, we have enlisted step-by-step process to write unit tests in Vue application using Jest Vue Test Utils.

Step 1: Creating Vue Component

Create a new component in the src/components folder named HtmlComponent.vue. Add code to your component.

Copy Text
<template>  
  <div class="htmlClass">
    <h1>{{ title }}</h1>
  </div>
</template>


<script>
export default {
  name: 'HtmlComponent',
  data() {
    return {
      title: 'Vue is awesome.',
    }
  },
}
</script>


<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped></style>

Step 2: Create Test File, Import Vue Component & Test Functionality from Test Utils

Now, create a test file in tests/unit named HtmlComponent.spec.ts. We will be importing our component here, mounting it using test utils functionality, and running test on it.

Copy Text
import HtmlComponent from '@/components/HtmlComponent.vue'
import { shallowMount } from '@vue/test-utils'

Step 3: Adding Test Cases in the Test File

Copy Text
describe('HtmlComponent', () => {
  it('should render correct contents', () => {
    const wrapper = shallowMount(HtmlComponent)
    let header = wrapper.find('.htmlClass h1')
    expect(header.exists()).toBe(true)
    expect(header.text())
      .toBe('Vue is awesome.')
  })
})

In the above code, the shallowMount method takes a component as an argument and returns its Vue instance and DOM node. After mounting our component, we will check if h1 inside .htmlClass exists or not using a combination of find, exists & toBe.

After that, we will check if our header element contains the same value as “Vue is awesome.” or not.

Step 4: Run the Test Case

Run the unit using npm, you will get the following result:

Copy Text
$ npm run test:unit

> [email protected] test:unit C:\Projects\Vue Tests\vue_3_jest_unit_testing
> vue-cli-service test:unit

 PASS  tests/unit/HtmlComponent.spec.js
  HtmlComponent
    √ should render correct contents (62 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        4.374 s, estimated 14 s
Ran all test suites.

Congrats, you have completed your first Unit Testing using Jest Vue Test Utils.

Step 5: Test different Test Cases of Vue Component

Now let us add some more test cases.

Copy Text
it('check text content to be as defined in variable', () => {
  const wrapper = shallowMount(HtmlComponent, {
    data () {
      return {
        title: 'I love Vue.'
      }
    }
  })
  let header = wrapper.find('.htmlClass h1')
  expect(header.text()).toBe('I love Vue.')
})

In the above code, we are changing the value of our title variable and testing if the value of our header element is the same. Let’s now run our test command.

Copy Text
$ npm run test:unit

> [email protected] test:unit C:\Projects\Vue Tests\vue_3_jest_unit_testing
> vue-cli-service test:unit

 PASS  tests/unit/HtmlComponent.spec.js
  HtmlComponent
    √ should render correct contents (68 ms)
    √ check text content to be as defined in varaible (12 ms)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        5.327 s
Ran all test suites.

Let’s add some inputs and buttons in our vue template.

Copy Text
<template>
  <div class="htmlClass">
    <h1>{{ title }}</h1>
    <form>
      <input type="text" id="firstName" v-model="firstName" />
      <input type="text" id="secondName" v-model="secondName" />
      <button @click="submitForm()" class="submitForm">Submit</button>
  </form>
  </div>
</template>

<script>
export default {
  name: 'HtmlComponent',
  data() {
    return {
      title: 'Vue is awesome.',
      firstName: '',
      secondName: '',
    }
  },
  methods: {
    submitForm() {
      this.$emit('submit form')
    },
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped></style>

Now that we have added some more elements in our template, let’s create new test cases.

Copy Text
test('should show the form element on the user output', () => {
    const wrapper = shallowMount(HtmlComponent)
    expect(wrapper.find('form').exists()).toBe(true)
  })

  test('should contain input fields in template', () => {
    const wrapper = shallowMount(HtmlComponent)
    expect(wrapper.find('form > input').exists()).toBe(true)
  })

  test('should have button', () => {
    const wrapper = shallowMount(HtmlComponent)
    expect(wrapper.find('button').exists()).toBe(true)
  })

To test our new test cases, let’s rerun our test command.

Copy Text
$ npm run test:unit

> [email protected] test:unit C:\Projects\Vue Tests\vue_3_jest_unit_testing
> vue-cli-service test:unit

 PASS  tests/unit/HtmlComponent.spec.js
  HtmlComponent
    √ should render correct contents (72 ms)
    √ check text content to be as defined in varaible (9 ms)
    √ should show the form element on the user output (12 ms)
    √ should contain input fields in template (11 ms)
    √ should have button (11 ms)

Test Suites: 1 passed, 1 total
Tests:       5 passed, 5 total
Snapshots:   0 total
Time:        4.733 s
Ran all test suites.

As shown above, all our cases have passed the checks.

For the final round, now we are going to check if our click event on button is working as intended or not.

Copy Text
test('trigger click event on button ', async () => {
    const wrapper = shallowMount(HtmlComponent)
    const button = wrapper.find('button')
    await button.trigger('click')
    expect(wrapper.emitted()).toHaveProperty('submit form')
  })

In the above code, we are triggering a click event using the trigger property.

Copy Text
$ npm run test:unit

> [email protected] test:unit C:\Projects\Vue Tests\vue_3_jest_unit_testing
> vue-cli-service test:unit

 PASS  tests/unit/HtmlComponent.spec.js
  HtmlComponent
    √ should render correct contents (77 ms)
    √ check text content to be as defined in variable (28 ms)
    √ should show the form element on the user output (10 ms)
    √ should contain input fields in template (8 ms)
    √ should have button (9 ms)
    √ trigger click event on button  (17 ms)

Test Suites: 1 passed, 1 total
Tests:       6 passed, 6 total
Snapshots:   0 total
Time:        4.514 s
Ran all test suites.

Now all our test cases have passed, indicating that “submit form” is being emitted when our button is clicked. With this, we can conclude our button is working exactly as we planned.

You can find the above solution to implement on the Github Repository.

Take Away

With this simple tutorial on Vue unit testing using Jest Vue Test, we hope you got to learn and try your hands on testing utilities in Vue. If you want to learn other tactics of Vue latest updates and new features, check out our Vue tutorials. Bacancy is the best Vue development company for your frontend development requirements providing lightweight, performant, cost effective, and result-oriented Vue applications.

Frequently Asked Questions (FAQs)

Here is how you can test Vue Js components using Jest Vue Test Utils.
Step 1: Creating Vue Component
Step 2: Create Test File, Import Vue Component & Test Functionality from Test Utils
Step 3: Adding Test Cases in the Test File
Step 4: Run the Test Case
Step 5: Test different Test Cases of Vue Component

Why Write Unit Test with Jest Vue Test Utils?

  • Better Documentation
  • Provide a safety net for your code
  • Help you identify and fix problems early in the development process
  • It is easier for developers to understand the functionality of your components
  • Do you still need more clarity on its usage and development possibilities?

    Discover More Possibilities

Build Your Agile Team

Hire Skilled Developer From Us

Subscribe for
weekly updates

newsletter

What Makes Bacancy Stand Out?

  • Technical Subject Matter Experts
  • 2500+ Projects Completed
  • 90% Client Retention Ratio
  • 12+ Years of Experience

Our developers primarily focus on navigating client's requirements with precision. Besides, we develop and innovate to deliver only the best solutions to our clients.

get in touch
[email protected]

Your Success Is Guaranteed !

We accelerate the release of digital product and guaranteed their success

We Use Slack, Jira & GitHub for Accurate Deployment and Effective Communication.

How Can We Help You?