Skip to content
Advertisement

vue-test-utils returns null for document.querySelector

I am writing unit tests for a Vue.js component that displays some radiobuttons and emits an event with the radio button id whenever a button is checked:

ApplicationElement.vue:

JavaScript

I wrote the following test for said component:

ApplicationElement.spec.js:

JavaScript

The test fails with: “TypeError: Cannot read property ‘id’ of null” If I remove the document.querySelector line from the chooseElement method in the component and emit the right id by hand, the test succeeds.

How can I get document.querySelector to work with vue-test-utils?

Advertisement

Answer

I know, this question is already a bit older, but I finally found a solution here. You need to attach your component with attachTo (since May 2021) to an html element. The solution looks like this:

JavaScript

As you already did, it is important to call wrapper.destroy() after each test. Little refactoring tip: Put wrapper.destroy() into an afterEach callback function. Here you can find more about attachTo.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement