I have been experimenting with testing whether a method is invoked in a Vue component when a specific button is clicked.
Initially, I found success using the following method:
it('should call the methodName when button is triggered', () => {
const methodNameSpy = jest.spyOn(wrapper.vm, 'methodName')
wrapper.find('.is-success').trigger('click')
expect(methodNameSpy).toBeCalled()
})
This approach worked well for certain components, but I encountered an error indicating that the method was not called in some other components:
Error: expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls: 0
I suspect why this simple test may be failing in this scenario, but I am unsure of how to address it or if it is indeed the root cause.
The specific component in question is a "tooltip"; once the save/close button is clicked, it closes and disappears. This could potentially explain why the test is failing as it may no longer locate the elements being tested.
Here are the relevant code snippets for the component and its respective tests:
component.vue
<template lang="html">
<div class="editresewin" @click.stop>
<div class="topbar">
<button
class="button is-danger"
@click="close"
>
<b-icon icon="close" />
</button>
<button
class="button is-success"
@click="save"
/>
<h2 class="...">Title</h2>
</div>
<div class="...">
<div class="...">
<label>Label</label>
<input .../>
</div>
</div>
</div>
</template>
component.spec.vue
describe('TheEditResourceFile', () => {
let wrapper
let defaultParams
beforeEach(() => {
defaultParams = {
localVue,
i18n,
router,
store,
propsData: {
args: {
title: '',
description: '',
},
type: 'file',
},
}
wrapper = shallowMount(TheEditResourceFile, defaultParams)
})
it('should trigger the save method', () => {
const saveSpy = jest.spyOn(wrapper.vm, 'save')
wrapper.find('.is-success').trigger('click')
expect(saveSpy ).toBeCalled()
})
})
Please let me know if further clarification is required.
Thank you for your assistance.
Edit: Incorrect code provided for failed test.