Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 891
Alexander Shpindler Avatar asked Apr 13 '18 15:04

Alexander Shpindler


2 Answers

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.

like image 196
acdcjunior Avatar answered Oct 17 '22 10:10

acdcjunior


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.

like image 31
Codeacula Avatar answered Oct 17 '22 08:10

Codeacula