How do I correct my unit test to correctly test for the below?
Method:
close(event) {
const element = !!event?.target?.closest('#target')
if (!element) {
this.isVisible = false
}
},
Jest test:
it('should hide visibility if element is false', () => {
const wrapper = shallowMount(AccountLogin, { mocks })
wrapper.vm.close()
expect(wrapper.vm.$data.isVisible).toBe(false)
})
If the
change()event is fired on the root element of your component, this should work:If the event is triggered on a child of root component element, you'll need to pass that child to
spyOn, so you mock that child'sclosest, instead of thewrappers. e.g:Why you need to find the exact element: this is
jsdom: it's not actual DOM. Events don't bubble.What the above does: it hijacks
.closest()method ofevent.target's element so it returnstrue.Which, in your case, will cause
to return
true, sothis.isVisible = truewill be executed.If you want to test that it's not executed when
#targetis not found, write a second test, with a.closest()mock returningfalseand test thatisVisiblehas not been set fromfalsetotrueupon invoking.close(). Doing more than that would be testing that HTML works as expected.I recommended you trust that it does.