Skip to content

Instantly share code, notes, and snippets.

@sigwyg
Last active January 20, 2020 11:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sigwyg/54873b5fa8b695b256612b2bc83082dc to your computer and use it in GitHub Desktop.
Save sigwyg/54873b5fa8b695b256612b2bc83082dc to your computer and use it in GitHub Desktop.
タイマー・コンポーネントのテスト(Vue + Jestの場合)
describe('destroy()の挙動', () => {
test('clearIntervalされているかどうか', () => {
// globalメソッドを上書きして、intervalIDを記録する
let intervals = []
window.mockSetInterval = window.setInterval
window.setInterval = function(func, interval) {
const intervalId = window.mockSetInterval(func, interval)
intervals = [...intervals, intervalId]
//console.log('window.setInterval:', intervalId, intervals)
return intervalId
}
// globalメソッドを上書きして、intervalIDを消していく
window.mockClearInterval = window.clearInterval
window.clearInterval = function(intervalId) {
window.mockClearInterval(intervalId)
console.log(window.mockClearInterval(intervalId))
intervals = intervals.filter(i => i !== intervalId)
//console.log('window.clearInterval:', intervalId, intervals)
}
// コンポーネントを破棄して、clearInterval()が叩かれたか確認する
// - 消去に成功したかどうかは判らない
const wrapper = factory({})
wrapper.destroy()
expect(intervals).toEqual([])
})
})
})
...
mounted() {
// 現在時の更新(タイマーなので)
const intervalId = setInterval(() => {
this.nowDate = new Date()
}, 1000)
/**
* ミリ秒をまともに返すと重そう&末尾しか変わらないため、
* それっぽく見せるため乱数にする
*
* - disableMsec
*
* @return {number} ランダムな2桁の数値
*/
const msec = this.$refs.msec
let intervalMsecId
if (!this.disableMsec && msec) {
intervalMsecId = setInterval(() => {
// 先頭はdecrement(9->8..0->9)
const msecValue = msec.innerText
const head = (parseInt(msecValue.slice(0, 1)) + 9) % 10
// 末尾がランダム
const tail = Math.floor(Math.random() * 10)
// 2桁表示(文字列として連結)
msec.innerText = `${head}${tail}`
}, 90)
}
// release setInterval()
// - ToDo: テストできる?
this.$once('hook:beforeDestroy', function() {
clearInterval(intervalId)
if (!this.disableMsec && msec) clearInterval(intervalMsecId)
})
},
}
describe('destroy()の挙動', () => {
test('clearIntervalされているかどうか', () => {
/**
* JestのuseFakeTimers()使うとネイティブのタイマー関数がモック関数に置き換えられる
*/
jest.useFakeTimers()
// コンポーネントを破棄して、clearInterval()が叩かれたか確認する
// - setInterval/clearIntervalが同じ回数叩かれた、くらいしか判らないが
const wrapper = factory({})
wrapper.destroy()
expect(setInterval.mock.calls.length).toBe(
clearInterval.mock.calls.length,
)
})
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment