'Mocking methods with jest and vue
I have been trying to test if a method is called in a Vue component when a specific button is triggered.
I've been successfull using this method at first:
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()
})
So this worked just fine for some components, but I still get an error telling me that it did not get called on some other components
Error: expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls: 0
I have one idea on why this simple test is failling in this case, but i have no idea on how to fix it or even if it is the reason.
This component is a "tooltip", once the save / close button is pressed, it closes, and disapears. Maybe that's why the test is failing, because it can't find the tested elements anymore.
Here is the component and the 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()
})
})
Let me know if more clafication is needed.
Thank you for your help.
Edit: Wrong code on failed test.
Solution 1:[1]
In Vue 2, the mock/spy on the component method must be done on the component's
.methodsdefinition -- not the wrapper -- before mounting. (As of Vue 3.2.31, this order is no longer required for methods called post-mount.)The
trigger('click')call needs to beawaited because it invokes the bound method asynchronously.The spy is always truthy, so
toBeTruthy()is a meaningless assertion. Instead, asserttoHaveBeenCalled()on the spy.
it('should trigger the save method', () => {
1??
const saveSpy = jest.spyOn(TheEditResourceFile.methods, 'save')
wrapper = shallowMount(TheEditResourceFile, defaultParams)
2??
await wrapper.find('.is-success').trigger('click')
3??
expect(saveSpy).toHaveBeenCalled()
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | tony19 |
