I'm trying to verify the behavior of a Vue form, based on Vuetify components, using Jest and Avoriaz.
I can trigger submit.prevent
on the form, resulting in expected behavior.
But triggering click
on the submit button does not work.
The component:
<template>
<v-form
ref="form"
data-cy="form"
@submit.prevent="login"
>
<v-text-field
id="email"
v-model="email"
label="Email"
name="email"
prepend-icon="mdi-at"
type="text"
required
autofocus
data-cy="email-text"
/>
<v-btn
color="primary"
type="submit"
data-cy="login-btn"
>
Login
</v-btn>
</v-form>
</template>
<script>
export default {
data () {
return {
email: '[email protected]',
}
},
computed: {},
methods: {
login: function () {
console.log('Logging in')
}
}
}
</script>
The test setup:
import vuetify from '@/plugins/vuetify'
import { mount } from 'avoriaz'
import Form from '@/views/Form'
describe('Form', () => {
const mountFunction = options => {
return mount(Form, {
vuetify,
...options
})
}
Where the Vue & Vuetify setup is done in @/plugins/vuetify
:
import Vue from 'vue'
import Vuetify from 'vuetify/lib'
Vue.use(Vuetify)
export default new Vuetify({
})
The following test succeeds (thus the mock works):
it('can trigger form directly', () => {
const login = jest.fn()
const wrapper = mountFunction()
wrapper.setData({ 'email': 'test@com' })
wrapper.setMethods({ login })
let element = wrapper.first('[data-cy=form]')
element.trigger('submit.prevent')
expect(login).toHaveBeenCalledTimes(1)
})
But actually testing the submit button, fails:
it('can trigger form through button', () => {
const login = jest.fn()
const wrapper = mountFunction()
wrapper.setData({ 'email': '[email protected]' })
wrapper.setMethods({ login })
const button = wrapper.first('[type=submit]')
button.trigger('click')
expect(login).toHaveBeenCalledTimes(1)
})
Update:
Perhaps some relevant dependencies in package.json
:
{
..
"dependencies": {
"axios": "^0.19.1",
"core-js": "^3.4.4",
"vue": "^2.6.11",
"vue-router": "^3.1.3",
"vuetify": "^2.1.0",
"vuex": "^3.1.2"
},
"devDependencies": {
..
"avoriaz": "^6.3.0",
"vue-jest": "^3.0.5",
"vuetify-loader": "^1.3.0"
}
}
Update:
When using test-utils, non Vuetify components (<form>
and <btn
), the following test succeeds:
const localVue = createLocalVue()
localVue.use(Vuetify)
describe('Form', () => {
const mountFunction = options => {
return shallowMount(Form, {
localVue,
vuetify,
...options
})
}
it('can trigger form through button alternative', async () => {
const login = jest.fn()
const wrapper = mountFunction({ attachToDocument: true })
try {
wrapper.setData({ 'email': '[email protected]' })
wrapper.setMethods({ login })
const button = wrapper.find('[type=submit]')
expect(button).toBeDefined()
button.trigger('click')
await Vue.nextTick()
expect(login).toHaveBeenCalledTimes(1)
} finally {
wrapper.destroy()
}
})
})
Then switching to Vuetify components cause the test to fail.