Trigger form submit on button click in Vue Unit Test Trigger form submit on button click in Vue Unit Test vue.js vue.js

Trigger form submit on button click in Vue Unit Test


Note: The previous method used attachToDocument, which has been deprecated,


The issue is that Vue Test Utils does not attach DOM nodes to the document by default. This is to avoid enforcing cleanup. You can solve this by setting attachTo to an HTML element when you mount the component:

const div = document.createElement('div')div.id = 'root'document.body.appendChild(div)it('button click triggers submit event', () => {  const wrapper = shallowMount(Form, {    attachTo: '#root'  })  wrapper.find("[type='submit']").trigger('click')  assert.exists(    wrapper.emitted('submitEventTriggered'),    'Form submit not triggered'  )})

You should remove the DOM node from the document to avoid a memory leak. You can do this by calling destroy on the wrapper:

wrapper.destroy()