During testing a vue component in jest document.querySelector always returns null
Asked Answered
J

2

12

This is my test:

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)
})

The code being tested:

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

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.

Jointed answered 13/4, 2018 at 15:48 Comment(0)
C
15

You have to attach it to the DOM explicitly:

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

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
})

You should remember to call wrapper.destroy() after you are done using it.

Clinkstone answered 13/4, 2018 at 16:6 Comment(0)
L
11

As of June 2020, vue-test-utils 1.3 has deprecated the use of attachToDocument. The solution that now works for me (as I had the same issue) is to replace it with:

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

You also need to call wrapper.destroy() at the end of your test so it doesn't affect the others.

Linkman answered 8/6, 2020 at 13:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.