[Advent Calendar 2021][Day17]ユニットテストを作る

undefined
はじめに
Advent Calendar 2021のDay17。 今回はユニットテストを書いていきます。
jest関連のインストール
ユニットテストでは定番のjestを使います。
yarn add --dev @types/jest jest ts-jest jest-transform-stub babel-jest @babel/preset-envyarn add --dev @vue/vue3-jest @vue/test-utils@next
こちらの記事を参考にさせていただきました。かなり詳しく解説されているので助かります。
https://medium.com/@fgoessler/set-up-nuxt3-with-jest-typescript-80aa4d3cfabc
基本的に修正しているファイルは上記で書かれていることのコピペです。
- babel.config.js
module.exports = { "presets": ["@babel/env"]}
- jest.config.js
// ./jest.config.js/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */module.exports = { preset: 'ts-jest', testEnvironment: 'jsdom', moduleFileExtensions: ["js", "jsx", "mjs", "ts", "vue"], moduleNameMapper: { "^@/(.*)": "<rootDir>/$1", "#app": "<rootDir>/node_modules/nuxt3/dist/app/index.mjs" }, transform: { '^.+\\.(js|jsx|mjs)$': 'babel-jest', '^.+\\.(ts|tsx)$': 'ts-jest', ".+\\.(css|scss|png|jpg|svg)$": "jest-transform-stub", ".*\\.(vue)$": "@vue/vue3-jest", }, transformIgnorePatterns: [ "node_modules/(?!(nuxt3|unenv))", ], setupFiles: [ "./test-utils/global-test-utils-config.ts" ]};
- tsconfig.json
{ // https://v3.nuxtjs.org/concepts/typescript "extends": "./.nuxt/tsconfig.json", "compilerOptions": { "types": [ "jest" ] }}
- test-utils/global-test-utils-config.ts
import { ref } from "vue";/** Mock Nuxt's useState to be a simple ref for unit testing. **/jest.mock("#app", () => ({ useState: <T>(key: string, init: () => T) => { return ref(init()) }}))
簡単なユニットテストを書く
Vueのテスティングフレームワークは、Vue Testing Library
というのもあるのですが、自分の環境では上手く動かせなかったです。直接vue/test-utils
を使う形で書いていきます。
- components/tests/Modal.test.ts
import { mount } from '@vue/test-utils'import Modal from '../Modal.vue'// The component to testtest('Modal test', () => { const wrapper = mount(Modal, { props: { title: 'Modal title', okLabel: 'Confirm', open: true, } }) wrapper.find('.btn.btn-primary').trigger('click') // Assert the rendered text of the component expect(wrapper.text()).toContain('Modal title') expect(wrapper.emitted()).toHaveProperty('ok')})
テストを実行します。下記のように成功すればOKでしょう。
$ yarn jestyarn run v1.22.5 PASS components/__tests__/Modal.test.ts ✓ Modal test (25 ms)Test Suites: 1 passed, 1 totalTests: 1 passed, 1 totalSnapshots: 0 totalTime: 3.242 s, estimated 5 sRan all test suites.Done in 4.12s.
ユニットテストをガッツリ書くというかは、Nuxt3でVueのユニットテストが書ける仕組みが出来ただけで良しとします。 個人的に、componentsのテストはユニットテストで行って、ページのテストはE2Eで良いかなと思っています。
まとめ
今回は、Nuxt3のユニットテストを書きました。 次回は、E2Eテストを書きます。
