LoginSignup
1
0

More than 1 year has passed since last update.

Vue2+Composition APIでVue Test Utilsのtrigger,emittedが機能しない時の対処方法

Posted at

概要

今後はVue3を使うことが多くなると思いますが、Vue2 + Composition APIを使う環境で、
triggerを行った結果イベントがemitされることを wrapper.emitted で検証しようとしても、
戻り値がundefinedしか取れずうまく行かない事象が起きてハマっていました。

  const expectedId = 'test-id'
  const wrapper = mount(SideMenuItem, {
    propsData: {
      id: expectedId,
      title: 'テスト',
    },
  })

  await wrapper.find('[data-test="menu-item"]').trigger('click')

  expect(wrapper.emitted('click')[0][0]).toBe(expectedId)
  // wrapper.emitted('click') の戻り値がundefinedでうまく行かない。
  // もう少し調べると emitted() の戻り値が空のオブジェクトになっている。

TL;DR

jest用に以下の設定ファイルを作成し、jest.config.js で指定する必要がありました。
Vue2ではComposition APIはプラグイン扱いなので、当然と言えば当然でした。

setup.js

import Vue from 'vue'
import CompositionApi from '@vue/composition-api'

Vue.use(CompositionApi)

jest.config.js

module.exports = {
  //中略
  setupFiles: ['./setup.js'],
}

詳細

コンポーネント

<template>
  <div>
    <div
      @click="handleClick"
      data-test="menu-item"
    >
      {{ title }}
    </div>
  </div>
</template>

<script>
import { defineComponent } from '@vue/composition-api'

export default defineComponent({
  props: {
    id: {
      type: String,
      required: true,
    },
    title: {
      type: String,
      required: true,
    },
  },
  setup(props, context) {
    const handleClick = () => {
      context.emit('click', props.id)
    }

    return {
      handleClick,
    }
  },
})
</script>

テスト

  it('クリック時にイベントがemitされること', async () => {
    const expectedId = 'test-id'
    const wrapper = mount(SideMenuItem, {
      propsData: {
        id: expectedId,
        title: 'テスト',
      },
    })

    await wrapper.find('[data-test="menu-item"]').trigger('click')

    expect(wrapper.emitted('click')[0][0]).toBe(expectedId)
  })
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0