When the change()
event occurs on the main element of your component, you can use this code:
jest.spyOn(wrapper, 'closest')
.mockImplementationOnce(() => true)
wrapper.vm.close()
expect(wrapper.vm.$data.isVisible).toBe(false)
If the event is triggered on a child element within the main component, you will have to specify that child in the spyOn
function and mock its closest
method instead of the main wrapper
. For example:
jest.spyOn(wrapper.find('input'), 'closest')
.mockImplementationOnce(() => true)
// ...
The reason for finding the exact element is because jsdom
does not fully replicate the actual DOM behavior and events do not bubble up.
What the above script accomplishes: it intercepts the .closest()
method of the target element so that it returns true
.
This action will result in
!!event?.target?.closest('#target')
returning true
, which leads to execution of this.isVisible = true
.
To ensure that this.isVisible
remains false when #target
cannot be found, create a second test with a .closest()
mock returning
false</code. Verify that <code>isVisible
does not change from
false
to
true
after calling
.close()
. It's best to trust that the HTML functions correctly rather than extensively testing it.