I am building a web application with nuxt js jest
My nuxt js component codes:
export default {
mounted () {
document.addEventListener('click', this.eventClick)
},
destroyed () {
document.removeEventListener('click', this.eventClick)
},
methods: {
eventClick () {
console.log('click event triggered!')
}
}
}
My codes in jest:
import Dashboard from '~/pages/admin/dashboard'
test('test click', () => {
wrapper = mount(Dashboard)
wrapper.trigger('click')
})
The problem is:
jest cannot fire click event and the code console.log('click event triggered!')
is not executed.
How can I fix the problem?
CodePudding user response:
The event listener is on the document
, so clicking the wrapper
would not trigger the click
event.
Instead, trigger the event on the document.body
:
test('test click', () => {
const eventClick = jest.spyOn(Dashboard.options?.methods || Dashboard.methods, 'eventClick')
shallowMount(Dashboard)
document.body.click()