I have a FileForm.vue component:-
<template>
<div class="file-form">
<form @submit="submit">
<input v-model="name" type="text" placeholder="File Name" />
<button type="submit">
<i class="fas fa-plus"></i>
</button>
</form>
</div>
</template>
<script>
export default {
data () {
return {
name: ''
}
},
methods: {
submit () {
if (!this.name.trim()) {
return
}
this.$emit('submit', this.name)
}
}
}
</script>
It is included in App.vue component:-
<template>
<div class="main">
<div class="sidebar">
<file-form @submit="createFile"></file-form>
<div class="files-list">
</div>
</div>
<div class="content">
<editor v-model="content"></editor>
<renderer :markdown="content"></renderer>
</div>
</div>
</template>
Now I am testing this behavior:-
test('on successfull submit of the FileForm.vue a file object should be pushed to files array of App.vue', () => {
let appWrapper = mount(App)
appWrapper.setMethods({
createFile: jest.fn()
})
appWrapper.find('form').trigger('submit')
expect(appWrapper.vm.createFile).toHaveBeenCalled()
})
It will fail because initially the FileForm.vue's input is empty and so it's data name property, it will not fire the submit action because of the if block. Therefore the mocked createFile is not been called.
If somehow I can set the data, which in this case the name property of the FileForm.vue before triggering the submit, my test will pass. Something like this:-
let formWrapper = appWrapper.find('file-form')
formWrapper.setData({
name: 'New File'
})
But I cannot do this, because formWrapper is an HTMLElement not a Vue Instance.
Use
import FileForm from '@/components/FileForm'
let formWrapper = appWrapper.find(FileForm)
formWrapper.setData({
// your code here
})