Nuxt.jsとTypeScriptの構築が難しいので、TypeScriptは入れていません。 今後、おそらく改善されていくと思うので、その時に頑張ろうかなと思います。
Testツールをインストールする。
yarn add -D jest vue-jest @vue/test-utils babel-jest
jest.config.js
を作成し、記述します。
module.exports = { transform: { "^.+\\.js$": "babel-jest", ".*\\.(vue)$": "vue-jest", }, moduleNameMapper: { "^@/(.*)$": "<rootDir>/$1", "^~/(.*)$": "<rootDir>/$1", }, moduleFileExtensions: ["js", "json", "vue"], testMatch: ["<rootDir>/tests/components/**/*.js"], // テストの対象(〇〇test.js) }
このままだと、import
文を読み込んでくれないので、コンパイルに必要なライブラリをインストールします。
yarn add -D babel-core@bridge
package.json
にbabelの設定を書きます。.babelrc
でも良いです。
{ ... "babel": { "env": { "test": { "presets": [ "@babel/preset-env" ] } } }, "scripts": { "test": "jest --config jest.config.js" }, ... }
lintでdescribe
やtest
が引っ掛かるので、.eslintrc.js
の追記します。
module.exports = { ignorePatterns: ["**/tests/**/**/*.js"], // 追記 }
このブログのディレクトリは下記のようになっています。TheTag.vue
のテスト作成します。
components ├── atoms │ └── TheTag.vue ├── molecules └── organisms tests └── components ├── atoms │ └── TheTag.test.js ├── molecules └── organisms
@components/atoms/TheTag.vue
のテストを作成します。hygenなどで作ってもいいかも。
<template> <a :href="`/tag/${tag.fields.slug}`"> {{ tag.fields.name }} </a> </template> <script> export default { name: "TheTag", props: { tag: { type: Object, required: true, }, }, } </script>
import { mount } from "@vue/test-utils" import TheTag from "@/components/atoms/TheTag" describe("TheTag", () => { const wrapper = mount(TheTag, { propsData: { tag: { fields: { name: "NuxtJS", slug: "nuxt", }, }, }, }) test("props", () => { expect(wrapper.props().tag.fields.name).toBe("NuxtJS") expect(wrapper.props().tag.fields.slug).toBe("nuxt") }) test("attributes", () => { const aTag = wrapper.find('a') const href = `/tag/${wrapper.props().tag.fields.slug}` expect(aTag.text()).toContain(wrapper.props().tag.fields.name) expect(wrapper.attributes().href).toBe(href) }) })
yarn test
設定しようと思ったら、error Command "husky-run" not found. #881が発生したので。。。
yarn add -D husky lint-staged yarn husky init
package.json
に追記する。これでGitコミット時にLinterとTestが実行されます。
{ "husky": { "hooks": { "pre-commit": "lint-staged" } }, "lint-staged": { "*.{js,vue}": "yarn lint", "*.{css,vue}": "yarn stylelint", "*.{js,vue}": "yarn test" }, }
stylelintも入れておくと、CSSのちらつきなど原因のわからないエラーを潰してくれたので良きです。