My example component shows a counter (initially "0") and an "increase" button. It looks something like this:
<div ref="label">{{ counter }}</div>
<div
ref="button"
@click="counter++"
>
Click me
</div>
If I test the click behaviour with Jest the following test will fail
it('increases the counter when the button is clicked', async () => {
const button = testComponent.findComponent({ ref: 'button' })
button.vm.$emit('click');
const label = testComponent.findComponent({ ref: 'label' })
expect(label.text()).toBe('1'); // fails
});
As I understand correctly, the event handler is called synchronously but the DOM update is still waiting in the async update queue of Vue. So to make the test work, I have to await Vue.$nextTick() for the DOM to be updated:
it('increases the counter when the button is clicked', async () => {
const button = testComponent.findComponent({ ref: 'button' })
button.vm.$emit('click');
await Vue.$nextTick();
const label = testComponent.findComponent({ ref: 'label' })
expect(label.text()).toBe('1'); // succeeds
});
But I can await anything for the DOM to be updated. I can literally await an empty object and the test will succeed:
it('increases the counter when the button is clicked', async () => {
const button = testComponent.findComponent({ ref: 'button' })
button.vm.$emit('click');
await {};
const label = testComponent.findComponent({ ref: 'label' })
expect(label.text()).toBe('1'); // succeeds
});
I can't figure out why this is. Is it a specific behaviour of Jest? Why is this working?