The Official Unit Testing Utility Library for Vue.js Is Now Available

News

October 10th, 2017

vue-official-testing-utils-1.png

Vue.js now has an official unit testing library for testing Vue applications. It provides methods for unit testing your components.

A 1.0 beta version shipped Monday, as well as an official guide to help you get started with standard tips, using test runners, and testing components which use Vuex (centralized state management for Vue).

Here’s an example of unit testing a Vue component with the utils library:

1import { mount } from 'vue-test-utils'
2import Counter from './counter'
3
4describe('Counter', () => {
5 // Now mount the component, and you have the wrapper.
6 const wrapper = mount(Counter)
7
8 it('renders the correct markup', () => {
9 expect(wrapper.html()).toContain('<span class="count">0</span>')
10 })
11
12 // It's also easy to check for the existence of elements.
13 it('has a button', () => {
14 expect(wrapper.contains('button')).toBe(true)
15 })
16})

According to the guide, here’s an overview of how vue-test-utils works:

vue-test-utils tests Vue components by mounting them in isolation, mocking the necessary inputs (props, injections and user events) and asserting the outputs (render result, emitted custom events).

Mounted components are returned inside a Wrapper, which exposes many convenience methods for manipulating, traversing and querying the underlying Vue component instance.

Taking the above example, you could interact with the counter and make assertions with the following as outlined in the documentation.

1it('button click should increment the count', () => {
2 expect(wrapper.vm.count).toBe(0)
3 const button = wrapper.find('button')
4 button.trigger('click')
5 expect(wrapper.vm.count).toBe(1)
6})

Check out the official guide and starter project to get familiar with testing Vue applications with the official test utils library.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.