[Vuejs]-Unit testing a vue component

0👍

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)
  });  
});

Leave a comment