【问题标题】:During testing a vue component in jest document.querySelector always returns null在 jest document.querySelector 中测试 vue 组件时,总是返回 null
【发布时间】:2018-09-24 00:57:11
【问题描述】:

这是我的测试:

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

而且它不仅在这个地方。代码中的每个 document.querySelector 在测试期间都返回 null。代码运行时好像没有渲染模板。

【问题讨论】:

    标签: javascript unit-testing vue.js jestjs gsap


    【解决方案1】:

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

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

    2021 年 5 月更新:attachToDocument 已弃用,不应再使用(参见VueTestUtils)。相反,您应该使用attachTo:

    const elem = document.createElement('div')
    if (document.body) {
      document.body.appendChild(elem)
    }
    wrapper = mount(Component, {
      attachTo: elem
    })
    

    你应该记得在使用完之后调用 wrapper.destroy()。

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        猜你喜欢
        • 2017-10-12
        • 2021-04-16
        • 2019-05-27
        • 1970-01-01
        • 2014-09-25
        • 2018-09-15
        • 2018-04-25
        • 2015-07-10
        • 1970-01-01
        相关资源
        最近更新 更多