nextTick
の使い方(DOMの更新待ち)(Composition API + Jest における Vue の非同期 DOM 更新)
Vue では
ref
/ reactive
の変更は即座に DOM に反映されない→ テストでは必ず await nextTick()
を使って「DOM更新完了」を待つ必要がある。
import { nextTick } from 'vue';
await nextTick(); // DOM更新を待つ
<!-- Counter.vue -->
<template>
<p>{{ count }}</p>
<button @click="increment">+</button>
</template>
<script lang="ts" setup>
import { ref } from 'vue';
const count = ref(0);
const increment = () => {
count.value += 1;
};
</script>
import { shallowMount } from '@vue/test-utils';
import Counter from '@/components/Counter.vue';
it('クリックで count が増える (NG例)', async () => {
const wrapper = shallowMount(Counter);
await wrapper.find('button').trigger('click');
// DOMが更新される前に確認してしまう
expect(wrapper.text()).toContain('1'); // ← ここで失敗することがある
});
→ 描画が終わる前に text()
してしまうため、失敗することがある。
nextTick
使用)】