'Vue Test Utils - data does not update after triggering click event
I have this basic test using Vue Test Utils:
import { mount } from '@vue/test-utils'
const App = {
template: `
<p>Count: {{ count }}</p>
<button @click="handleClick">Increment</button>
`,
data() {
return {
count: 0
}
},
methods: {
handleClick() {
this.count += 1
}
}
}
test('it increments by 1', async () => {
const wrapper = mount(App, {
data() {
return {
count: 0
}
}
})
expect(wrapper.html()).toContain('Count: 0')
await wrapper.find('button').trigger('click')
expect(wrapper.html()).toContain('Count: 1')
})
The test only passes if I either
- don't send any custom data to the mount method, or
- force a re-render, using
wrapper.vm.$forceUpdate()after triggering the event.
However, according to the documentation, shouldn't it just pass as it is already written?
Solution 1:[1]
The test is fine, in vue2 you have to add a root to the template. Component template should contain exactly one root element.
<div>
<p>Count: {{ count }}</p>
<button @click="handleClick">Increment</button>
</div>
Solution 2:[2]
import { mount } from '@vue/test-utils'
const sleep = (ms: number) => {
return new Promise((resolve) => setTimeout(resolve, ms));
}
const App = {
template: `
<p>Count: {{ count }}</p>
<button @click="handleClick">Increment</button>
`,
data() {
return {
count: 0
}
},
methods: {
handleClick() {
this.count += 1
}
}
}
test('it increments by 1', async () => {
const wrapper = mount(App, {
data() {
return {
count: 0
}
}
})
expect(wrapper.html()).toContain('Count: 0')
await wrapper.find('button').trigger('click')
await wrapper.vm.$nextTick();
await sleep(2000);
expect(wrapper.html()).toContain('Count: 1')
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mk_xt |
| Solution 2 | ajeesh s |
