LoginSignup
0
1

More than 3 years have passed since last update.

Vueコンポーネントをもっと「効率的にテストする」

Posted at

初めに

vueのテストでコンポーネントを生成する際、
- 基本的にデフォルト値を使用
- 必要な値だけ変更
という感じで簡単に生成できるよう考えました。

Vuetifyの「効率的にテストする」の以下のようにしても良いですが
「これだと結局propsData全部指定しなきゃいけないし増えたらケース毎に指定するの面倒じゃない?」
と思ったのが発端です。

やってみる

元のソースコード

「効率的にテストする」から引用

  const mountFunction = options => {
    return mount(CustomCard, {
      localVue,
      vuetify,
      ...options,
    })
  }

  it('should have a custom title and match snapshot', () => {
    const wrapper = mountFunction({
      propsData: {
        title: 'Fizzbuzz',
      },
    })

    expect(wrapper.html()).toMatchSnapshot()
  })

いじったあとのソースコード

デフォルト値を指定

  // デフォルトの値を指定
  const defaultOptions = {
    title: 'Fizzbuzz',
    text: 'hogehoge',
  }

  const mountFunction = (options=defaultOptions) => {
    return mount(CustomCard, {
      localVue,
      vuetify,
      propsData: Object.assign(defaultOptions, options),
    })
  }

  it('デフォルトの値をそのまま利用する場合', () => {
    const wrapper = mountFunction() // 値を気にしなくて良いテストはそのままデフォルト値を使用
    expect(wrapper.html()).toMatchSnapshot()
  })

  it('複数のpropsの中で一つだけ変更したい場合', () => {
    const wrapper = mountFunction({ title: 'BuzzFizz' }) // 必要な値だけ更新してテスト
    expect(wrapper.html()).toMatchSnapshot()
  })

まとめ

ただの表示確認ならmountFunction()でいいですし
一つのプロパティに値を設定してその結果を見たいならmountFunction({ key: value })で、そのプロパティ以外の無駄なコードを省けますし使えるかも!
とvue始めたての初心者が思いついた記事でした。
ありきたりかもしれませんが備忘録的な意味も込めて。

もっと良い方法なんかがあれば教えてください!

以上です。

0
1
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
0
1