LoginSignup
5
9

More than 3 years have passed since last update.

Nuxt.js に後からテスト (Jest/vue-test-utils)を入れる

Last updated at Posted at 2019-12-24

概要

Nuxt.js のプロジェクトに後から Jest と vue-test-utils を入れる機会があったのでメモしておきます。

必要なライブラリをインストール

yarn add -D @babel/plugin-transform-runtime @babel/preset-env @vue/test-utils jest vue-jest babel-core vue-jest

.babelrc を追加

プロジェクトのルート直下に .babelrc を追加します。

// .babelrc

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "useBuiltIns": false,
        "targets": {
          "node": "current"
        }
      }
    ]
  ],
  "plugins": [
    "@babel/plugin-transform-runtime"
  ]
}

jest.config.js を追加

続いて jest.config.js を追加します。

module.exports = {
  transform: {
    '^.+\\.js$': 'babel-jest',
    '.*\\.(vue)$': 'vue-jest'
  },
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/$1',
    '^~/(.*)$': '<rootDir>/$1'
  },
  moduleFileExtensions: ['js', 'json', 'vue']
}

package.json に test script を追加

追加します。

"scripts": {
  ..
  "test": "jest --config jest.config.js"
},

これで yarn run test でテストを実行することができます。

テストを追加

ここでは、userInfo のみを props にもつ UserInfoCard というコンポーネントをテストします。テストは .user-name という CSS クラスの中にユーザー名が表示されるかのテストです。

// test/components/userInfoCard.spec.js
import { mount } from '@vue/test-utils'
import UserInfoCard from '~/app/components/UserInfoCard.vue'
import UserFixture from '@fixture/user'

describe('UserInfoCard', () => {
  test('Display text', () => {
    const wrapper = mount(UserInfoCard, { propsData: { userInfo: UserFixture } })
    expect(wrapper.find('.user-name').text()).toEqual('Test Name')
  })
})

テストで propsData を渡す時の hash key 名は、コンポーネントが受け取る props 名と合わせる必要があります。テストデータは fixture として別ファイルで定義してあげると使いまわせて便利です。

// test/fixtures/user.js
export default {
  id: 1,
  name: 'Test Name',
  ..
}

fixture 用の name mapperjest.config.js に追加してあげると良いです。

module.exports = {
  transform: {
    '^.+\\.js$': 'babel-jest',
    '.*\\.(vue)$': 'vue-jest'
  },
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/$1',
    '^~/(.*)$': '<rootDir>/$1',
    "^@fixture/(.*)$": "<rootDir>/test/fixtures/$1" // 追加
  },
  moduleFileExtensions: ['js', 'json', 'vue']
}

テスト実行

yarn run test でテスト実行してみましょう!
テストは通りましたか?

終わりに

テストを入念に書くコンポーネントとそうでないコンポーネントを見極めた上で、テストを書いていきましょう。それでは良いテストライフを! :thumbsup:

5
9
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
5
9