【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のテストサンプルも作成する予定
参考
Author And Source
この問題について(【Nuxt.js】 Jestを使ってコンポーネントのテスト書く), 我々は、より多くの情報をここで見つけました https://qiita.com/nakano-shingo/items/1b623353300d52255c6c著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .