【Nuxt.js】 Jestを使ってコンポーネントのテスト書く


今までフロントエンドでテストケースを書いたことがありませんでしたが、とある案件で挑戦する機会があったのでやってみました

やりたいこと

  • 作成済みの Nuxt.jsアプリに、後からJestを導入する
  • コンポーネントにpropsで渡した値が表示されるか確認するのテストを用意して実行する

事前準備

ライブラリのインストール

  • NuxtアプリでJestを動かすために必要なライブラリが入っていない場合は導入する
    (警告を消すために色々と入れましたが、全部は必要ないかもです)
yarn add -D @babel/core @nuxt/babel-preset-app @vue/test-utils babel-core babel-jest babel-preset-env jest vue-jest vue-template-compiler

設定ファイルの用意

Nuxtアプリのルートディレクトリ直下に用意

jest.config.js
module.exports = {
  transform: {
    '^.+\\.js$': 'babel-jest',
    '.*\\.(vue)$': 'vue-jest'
  },
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/$1',
    '^~/(.*)$': '<rootDir>/$1'
  },
  moduleFileExtensions: ['js', 'json', 'vue']
}
.babelrc
{
  "presets": [
    ["env", {
      "modules": false
    }]
  ],
  "env": {
    "test": {
      "presets": [
        ["env", {
          "targets": {
            "node": "current"
          }
        }]
      ]
    }
  }
}

コンポーネント作成

propsにtextを渡して、それを表示させるだけのシンプルなコンポーネントです

Button.vue
<template>
  <nuxt-link>
    {{ text }}
  </nuxt-link>
</template>

<script>
export default {
  props: {
    text: {
      type: String,
      required: true
    }
  }
}
</script>

テストケース作成

test/components/Button.spec.js
import { mount } from '@vue/test-utils'
import Button from '~/components/shared/Button'

describe('Button', () => {
  test('Display text', () => {
    const props = {
      text: '検索する'
    }
    const wrapper = mount(Button, {
      propsData: props
    })
    // propsに指定したデータが正しく表示されること
    expect(wrapper.props('text')).toBe(props.text)
  })
})

今回は簡単なpropsの表示テストだけですが、追って別記事でVuexのテストサンプルも作成する予定

参考