22nd October, 2020 | John | VUE

Testing Vue Applications With The Vue Testing Library

Cullinan
“The vue testing library can help you to test your applications by mirroring the way that a user would interact with them”

Here’s everything you need to know if you want to get started right away.

In this article, we will look at testing Vue applications using the Vue Testing Library — a lightweight library that emphasizes testing your front-end application from the user’s perspective.

The following assumptions are made throughout this article:

  • The reader is familiar with Vue.
  • The reader is familiar with testing application UI.

Conventionally, in Vue userland, when you want to test your application, you reach out for @vue/test-utils — the official testing library for Vue. @vue/test-utils provides APIs to test instances of rendered Vue components. Like so:


    // 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, {
                propsData: { msg }
            })

            expect(wrapper.text()).toMatch(msg)
        })
    })

You can see we are mounting an instance of the Vue component using the shallowMount function provided by @vue/test-utils.

The problem with the above approach to testing Vue applications is that the end-user will be interacting with the DOM and has no knowledge of how Vue renders the UI. Instead, he/she will be finding UI elements by text content, the label of the input element, and some other visual cues on the page.

A better approach will be writing tests for your Vue applications in such a way that mirrors how an actual user will interact with it e.g looking for a button to increment the quantity of a product in a checkout page, hence Vue Testing Library.

If you’d like more information on any of our services, then please Contact Us directly.

Let’s Get in Touch

We’re interested in talking
about your business.