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?
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With