I have a component that looks like this,
<template>
<!-- eslint-disable vue/no-v-html -->
<div class="c-dialog" :class="{'u-block': show}" @triggerOpen="handleOpen">
<div class="c-dialog__background" @click="handleClose">
<div class="c-dialog__wrapper u-mt-4 u-mb-1">
<div class="c-dialog__action u-flex">
<button class="c-dialog__close u-bg-denim-blue u-border-0 u-text-white" @click="handleClose">Close</button>
</div>
<div class="c-dialog__main u-px-2 u-py-4 u-border u-bg-white">
<h4>{{ content.title }}</h4>
<div class="c-dialog__content u-mt-2" v-html="content.content" />
</div>
</div>
</div>
</div>
I am wanting to unit test it, but I am very rusty when it comes to unit testing, the component is very simple, it is either show or hidden based on data value (show: true/false).
I assume that I would need 1 test for asserting that the component is hidden when show = false and another for asserting that modal is visible when show = true. But in a component that is so simple should I be unit testing anything else? There are 2 methods in the component handleClose (sets show to false) and handleOpen (sets show to true), does these methods need there own tests also? So far my test looks like,
import { shallowMount } from '@vue/test-utils'
import Dialog from './Dialog.vue'
test('Dialog', () => {
});
Something like this should test the open / close state.
You can also use jest.spy to see if the correct methods are called, but in this case testing the result should be fine.
The v-html is also something you could consider testing.
The snapshot tests are real nice to see if the state changes correctly, and it's implicitly testing your class assignment to.
import { shallowMount } from '@vue/test-utils'
import Dialog from './Dialog.vue'
function mountWith() {
return shallowMount(Dialog, {
data() {
return {
open: false,
...data
}
}
});
}
describe('Dialog', () => {
let wrapper;
afterEach(() => {
wrapper.destroy()
})
it('should mount successfully', () => {
wrapper = mountWith()
expect(wrapper.exists()).toBe(true)
});
it('should match snapshot in initial state', () => {
wrapper = mountWith()
expect(wrapper).toMatchSnapshot()
});
it('should match snapshot while open', () => {
wrapper = mountWith({ open: true })
expect(wrapper).toMatchSnapshot()
});
it('should open on c-dialog click', async () => {
wrapper = mountWith()
wrapper.find('.c-dialog').trigger('click');
await Vue.nextTick()
expect(wrapper.vm.open).toBe(true)
});
it('should close on background click ', async () => {
wrapper = mountWith({ open: true })
wrapper.find('.c-dialog__background').trigger('click');
await Vue.nextTick()
expect(wrapper.vm.open).toBe(false)
});
it('should close on dialog close click ', async () => {
wrapper = mountWith({ open: true })
wrapper.find('.c-dialog__close').trigger('click');
await Vue.nextTick()
expect(wrapper.vm.open).toBe(false)
});
});