在 jest document.querySelector 中测试 vue 组件时总是 returns 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})

开玩笑的错误信息:

Expected value to be:
  <a class="callback__phone link" href="tel:88619442620">+7 (861) 944 26 20</a>
Received:
  null

而且不止这个地方。测试期间代码 returns 中的每个 document.querySelector 为空。当代码为 运行.

时,看起来模板未呈现

您必须明确地将其附加到 DOM:

const wrapper = shallow(Component, {
  // ...
  attachToDocument: true
})

2021 年 5 月的更新:attachToDocument 已弃用,不应再使用(参见 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()。

截至 2020 年 6 月,vue-test-utils 1.3 has deprecated 使用 attachToDocument。现在对我有用的解决方案(因为我遇到了同样的问题)是将其替换为:

const wrapper = shallow(Component, {
  // ...
  attachTo: document.body
});

您还需要在测试结束时调用 wrapper.destroy(),以免影响其他人。