🎯 5.2 nextTick の使い方(DOMの更新待ち)

(Composition API + Jest における Vue の非同期 DOM 更新)


✅ 【要点】

Vue では

テストでは必ず await nextTick() を使って「DOM更新完了」を待つ必要がある


🟢 【基本の使い方】

import { nextTick } from 'vue';

await nextTick(); // DOM更新を待つ


🟠 【なぜ必要?(例:クリックで count を増やす)】

<!-- 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>


❌ 【nextTick なしのテスト(失敗例)】

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 使用)】