LoginSignup
23
12

More than 3 years have passed since last update.

Vue.jsでmethodsのテストを書く方法

Last updated at Posted at 2019-12-19

公式とかみてもあんま直接的な情報はなかったので。
複数人で開発していると、本来サーバー側でやってほしい処理などがmethodsとかに入り込みがちですよね。
誰もメンテできなくなる前にしっかりとテストコードを書いておき、いつでもリファクタリングできる状態をキープしておきたいものです。

環境

  • vue-test-utils
  • jest

テスト環境の構築方法などはvue-test-utilsjestの公式を参考にしてください。

サンプル

こんな感じのかなり尖ったコンポーネントがあるとします。

<template>
  <button @click="sampleMethod()" />
</template>
<script>
export default {
  methods: {
    sampleMethod() {
      return 'hello'
    }
  }
}
</script>

このコンポーネントのmethodsのテストは下記のように書くことができます。

import { createLocalVue, shallowMount } from '@vue/test-utils'
import Vuex from 'vuex'

import SampleComponent from '~/components/SampleComponent'

const localVue = createLocalVue()
localVue.use(Vuex)

describe('SampleComponent', () => {
  let wrapper

  beforeEach(() => {
    wrapper = shallowMount(UseHighway, { localVue })
  })

  it('sampleMethodsのテスト', () => {
    expect(wrapper.vm.sampleMethod).toBe('hello') // 通る
  })

  it('sampleMethodsのテスト(落ちるパターン)', () => {
    expect(wrapper.vm.sampleMethod).toBe('hey') // NG
  })
})

解説

vue-test-utilsのドキュメントには、

wrapper.vm を使って vm のプロパティとインスタンスメソッドにアクセスできます。これは、Vue コンポーネントのラッパもしくは Vue コンポーネントをバインディングしている HTMLElement のラッパにのみ存在します。

とあります。なので、上記のコードにおいてはwrapper.vmmethodsを呼び出せるわけですね。
実際には上記のコードのように副作用の全くないコードは珍しく、実際にはsetPropssetDataなどで値をセットしてからテストすることになると思います。

まとめ

エンジニアとして、やはりフロントエンドにおいてもできるだけ副作用が少なく、テストしやすいコードを書くことを意識していきたいですね。

23
12
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
23
12