在 jest document.querySelector 中测试 vue 组件时总是返回 null [英] During testing a vue component in jest document.querySelector always returns null
问题描述
这是我的测试:
jest.mock('gsap')
import TweenMax from '../../__mocks__/gsap'
import Component from '@/components/Callback/Form.vue'
import { shallow, createLocalVue } from '@vue/test-utils'
const localVue = createLocalVue()
test('phone opacity changing from 1 to 0 in totalTime', () => {
const wrapper = shallow(Component, {
localVue,
mocks: {
localStorage
},
watch: {
step
},
methods: {
enterNamePlaceholder,
toNextBtn
}
})
const phone = wrapper.find('.callback__phone')
expect(TweenMax.to.mock.calls[0][0]).toBe(phone.element)
})
正在测试的代码:
TweenMax.to(document.querySelector('.callback__phone'), this.totalTime, {opacity: 0, onComplete: this.enterNamePlaceholder})
还有开玩笑的错误信息:
And jest error message:
Expected value to be:
<a class="callback__phone link" href="tel:88619442620">+7 (861) 944 26 20</a>
Received:
null
而且它不仅在这个地方.代码中的每个 document.querySelector 在测试过程中都返回 null.代码运行时似乎没有呈现模板.
Moreover it's not only in this place. Every document.querySelector in the code returns null during testing. It looks like the template isn't rendered when the code is running.
推荐答案
您必须将其显式附加到 DOM:
You have to attach it to the DOM explicitly:
const wrapper = shallow(Component, {
// ...
attachToDocument: true
})
2021 年 5 月更新:attachToDocument 已弃用,不应再使用(参见 VueTestUtils).相反,您应该使用 attachTo:
Update from May 2021: attachToDocument is deprecated and should not be used anymore (see in VueTestUtils). Instead you should use attachTo:
const elem = document.createElement('div')
if (document.body) {
document.body.appendChild(elem)
}
wrapper = mount(Component, {
attachTo: elem
})
你应该记得在使用完后调用 wrapper.destroy().
You should remember to call wrapper.destroy() after you are done using it.
这篇关于在 jest document.querySelector 中测试 vue 组件时总是返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!