[英]Using DOM directly in Vue unit test when no alternative
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:如果在组件的根元素上触发了change()
事件,则应该可以:
jest.spyOn(wrapper, 'closest')
.mockImplementationOnce(() => true)
wrapper.vm.close()
expect(wrapper.vm.$data.isVisible).toBe(false)
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's closest
, instead of the wrapper
seg:如果事件在根组件元素的子元素上触发,则需要将该子元素传递给spyOn
,因此您模拟该子元素的closest
的,而不是wrapper
段:
jest.spyOn(wrapper.find('input'), 'closest')
.mockImplementationOnce(() => true)
// ...
Why you need to find the exact element: this is jsdom
: it's not actual DOM.为什么你需要找到确切的元素:这是jsdom
:它不是真正的 DOM。 Events don't bubble.事件不会冒泡。
What the above does: it hijacks .closest()
method of event.target
's element so it returns true
.上面做了什么:它劫持了event.target
元素的.closest()
方法,所以它返回true
。
Which, in your case, will cause在您的情况下,这将导致
!!event?.target?.closest('#target')
to return true
, so this.isVisible = true
will be executed.返回true
,所以this.isVisible = true
将被执行。
If you want to test that it's not executed when #target
is not found, write a second test, with a .closest()
mock returning false
and test that isVisible
has not been set from false
to true
upon invoking .close()
.如果您想测试在#target
时它没有执行,请编写第二个测试,使用.closest()
模拟返回false
并测试isVisible
在调用.close()
时没有从false
设置为true
。 Doing more than that would be testing that HTML works as expected.做更多的事情就是测试 HTML 是否按预期工作。
I recommended you trust that it does.我建议你相信它确实如此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.