🎯 2.2 Composition API でのテストの特徴(setup からの返り値は template 内)


✅ 【要点】

Composition API では、

そして

テスト時は「DOM経由」や「イベント経由」で確認する必要がある


🟢 【Composition API の基本パターン】

<!-- Counter.vue -->
<template>
  <div>
    <p>{{ count }}</p>
    <p>{{ double }}</p>
    <button @click="increment">+</button>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue';

const count = ref(0);
const double = computed(() => count.value * 2);
const increment = () => {
  count.value += 1;
};
</script>


🧪 【テストでできること / できないこと】

内容 クラスコンポーネント Composition API
count に直接アクセス wrapper.vm.count ❌ → DOM から取得 (wrapper.text() など)
double を直接確認 wrapper.vm.double ❌ → DOM から確認
increment を直接呼ぶ wrapper.vm.increment() ❌ → ボタンをクリックする(trigger

🟠 【テストコード例(Composition APIの場合)】

// tests/Counter.spec.ts
import { shallowMount } from '@vue/test-utils';
import Counter from '@/components/Counter.vue';

describe('Counter.vue (Composition API)', () => {
  it('初期 count が 0 で double も 0', () => {
    const wrapper = shallowMount(Counter);
    expect(wrapper.text()).toContain('0'); // ← DOM で確認
  });

  it('ボタンをクリックすると count が増える', async () => {
    const wrapper = shallowMount(Counter);
    await wrapper.find('button').trigger('click'); // ← increment を呼ぶ
    expect(wrapper.text()).toContain('1');         // ← 1 が表示されることを確認
    expect(wrapper.text()).toContain('2');         // ← double も確認
  });
});


🟣 【Composition API の場合の確認ポイント】