It took me a while to realize that testing functional components with vue-test-utils can present some challenges
In my case, I am utilizing Bootstrap-Vue's B-Button
with a @click
event that calls a function/method. When I attempt to test whether the method is being called, the test fails. However, if I switch the functional B-Button
with a regular <button>
, the test passes.
Below is the code snippet for the JobSearch.vue
component:
<template>
<b-input-group>
<b-form-input
class="mr-2 rounded-0"
placeholder="Enter Search term..."
id="input-keyword"
/>
<!-- <b-button-->
<!-- @click="searchJobs"-->
<!-- class="rounded-0 ml-2"-->
<!-- variant="primary"-->
<!-- id="reset-button"-->
<!-- >-->
<!-- Reset-->
<!-- </b-button>-->
<button
@click="resetFilter"
class="rounded-0 ml-2"
id="reset-button">
Reset
</button>
</b-input-group>
</template>
<script>
export default {
name: 'job-search-test',
methods: {
async searchJobs () {
console.log('Calling Search Jobs from JobsSearchTest')
},
resetFilter () {
console.log('Clicked On Reset')
}
},
mounted () {
// this.searchJobs()
}
}
</script>
And here is the content of JobSearch.spec.js
:
import { shallowMount, createLocalVue } from '@vue/test-utils'
import BootstrapVue from 'bootstrap-vue'
import JobSearchTest from '@/components/jobs/JobSearchTest'
const localVue = createLocalVue()
localVue.use(BootstrapVue)
describe('JobsSearchTest.vue', () => {
it('should call searchJobs method when component is mounted', () => {
let searchJobs = jest.fn()
shallowMount(JobSearchTest, {
methods: {
searchJobs
},
localVue })
expect(searchJobs).toHaveBeenCalledTimes(1)
})
it('should call resetFilter method on reset button click event', () => {
let resetFilter = jest.fn()
const wrapper = shallowMount(JobSearchTest, {
methods: {
resetFilter
},
localVue
})
expect(resetFilter).not.toHaveBeenCalled()
wrapper.find('#reset-button').trigger('click')
console.log(wrapper.find('#reset-button'))
expect(resetFilter).toHaveBeenCalled()
})
})
I have noticed that by switching between using <b-button>
and <button>
, the test outcome changes. Is there a way to keep the tests consistent without compromising the use of Bootstrap Vue for this project?
If you have any ideas or workarounds that could solve this issue without devaluing the test results, please share them. For instance, in a previous query, it was mentioned that functional components do not always work well with directives. Therefore, using a non-functional stub may resolve the directive issue but at the expense of accurate testing.
Use more than one directive to add data attributes to components