Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger form submit on button click in Vue Unit Test

Is there a way to actually trigger the submission of a form by clicking on a submit button in a Vue Unit Test?

Let's take this simple component:

<template>
    <form @submit.prevent="$emit('submitEventTriggered')">
        <button type="submit">Submit Form</button>
    </form>
</template>

<script>
    export default {}
</script>

You can find a similar component as an example here.

I want to test that submit.prevent gets triggered when the button is clicked and therefore the submitEventTriggered is emitted. When I run this in a browser everything works as expected, but the following test fails:

import {shallowMount} from '@vue/test-utils'
import {assert} from 'chai'
import Form from '@/components/Form.vue'

describe.only('Form', () => {

    it('button click triggers submit event', () => {
        const wrapper = shallowMount(Form)

        wrapper.find('[type=\'submit\']').trigger('click')

        assert.exists(wrapper.emitted('submitEventTriggered'), 'Form submit not triggered')
    })
})

With this output:

AssertionError: Form submit not triggered: expected undefined to exist

If I change the action to trigger submit.prevent on the form directly everything works fine, but then there is actually no test coverage for the submitting via button.

wrapper.find('form').trigger('submit.prevent')

It seems like the trigger function doesn't actually click the button.

Why is this and is there a way to fix it?

like image 918
Marvin Rabe Avatar asked Nov 19 '18 20:11

Marvin Rabe


1 Answers

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()
like image 72
Edward Avatar answered Sep 18 '22 09:09

Edward