そうだ、教祖になろう。出エジプト記 第4章7節 クライアントサイドのユニットテストをカバレッジ100%にする
寝乱れて 隠れ宿
現在、年末年始休みで東北に来ております。
近年は暖冬で雪が少ないものの、川とランデブーする単線の列車は旅情がありますね。
九十九折り 浄蓮の滝
第4章6節 クライアントサイドを自動テストするでJestを導入し、ユニットテストを実施しました。
カバレッジ100%になってなかったので、続きをやっていきます。
別に100%にしないといけないわけじゃないのですが、最初なんで今後のサンプルということで。
まずは、src/store/index.js
をテストするtests/unit/store/index.spec.js
です。
import store from '@/store' import * as types from '@/store/mutation-types' const state = store.state describe('store/index.js', () => { beforeEach(() => { jest.spyOn(console, 'log') jest.spyOn(console, 'error') }) afterEach(() => { console.log.mockRestore() console.error.mockRestore() }) it('正:初期状態', () => { expect(state.list).toEqual([]) }) it('正:list格納', () => { let list = [ 'あなたはアジアの小国の王子に生まれ変わりました。', 'アジアの小国の王子は今から980年前に生まれました。', '民に敬われた王の嫡男として生き', '50歳で死にました。', ] store.commit(types.STORE_LIST, {list: list}) expect(state.list).toEqual(list) }) })
STORE_LIST
をコミットして与えたリストと同じであることをアサーションしています。
console.log()
やconsole.error()
もspyOn
して想定外の出力がないことを確認します。
続いて、src/main.js
をテストするtests/unit/main.spec.js
です。
import axios from 'axios' jest.mock('axios') describe('main.js', () => { beforeEach(() => { jest.spyOn(console, 'log') jest.spyOn(console, 'error') axios.get.mockResolvedValue({}) }) afterEach(() => { console.log.mockRestore() console.error.mockRestore() }) it('正:初期状態', () => { /* eslint-disable no-unused-vars */ var main = require('@/main') expect(console.log).not.toHaveBeenCalled() expect(console.error).toHaveBeenCalledTimes(1) }) })
同じようにconsole.log()
をspyOn
。
Ajax処理が走らないようにaxios.get
モックします。
ま、今のプログラムはLife.vue
以外ほとんど何もしていないのでこんなもんです。
テストを実行します。
めでたくカバレッジ100%になりました。
あーすっきり。
あなたと越えたい 天城越え
もうすぐ年越しですね。
みなさまの令和二年が素晴らしい年になりますように。