Vue Test Utilsでコンポーネントのdata()を評価したい
なぜかうまくいかず時間がかかったのでメモ
こういうページネーションのコンポーネントのテストを書くとき、
コンポーネントのpropsには以下のような値(現在のページ,ページあたりの件数,トータル件数)を設定できるとして
<Pagination :config="{ current: 1, limit: 20, total: 100 }" @movePage="load" />
propsに値を設定したことを受け、watch
に定義したメソッドで、data()
の最終ページ lastPage
の値を算出したい。
watch: { config: function(payload) { // ここではわかりやすく「5ページ >>」とか変数にいれてる this.lastPage = Math.ceil(payload.total / payload.limit) + 'ページ >>' // 上記例の設定値だと「5ページ >>」になる } }
この「5ページ >>」を検査したかったのだけど、テストコードで propsData
をセットしてもなぜかwatchが発火しない。
<template> ... <a class="pagination-link last-page" :disabled="currentPage === lastPage" aria-label="Goto last page" @click="moveLast" > {{ lastPage }} <!-- 「5ページ >>」 --> </a> ... </template>
describe('components/Pagination.vue', () => { let wrapper describe('template', () => { beforeEach(() => { wrapper = mount(Pagination, { propsData: { config: { nextPage: 2, limit: 20, total: 100 } } // propsにセットしたのだからwatch発動してほしい! }) }) test('最終ページは5ページ目であること', () => { const page = wrapper.find('.last-page') expect(page.text()).toBe('5ページ >>') // 失敗。got:null }) }) })
props
を2回セットしたら思った通り動くようになった。
describe('components/Pagination.vue', () => { let wrapper describe('template', () => { beforeEach(() => { wrapper = mount(Pagination, { propsData: { config: { nextPage: 2, limit: 20, total: 100 } } }) }) test('最終ページは5ページ目であること', () => { wrapper.setProps({ config: { nextPage: 2, limit: 20, total: 100 } }) // これを足した。 const page = wrapper.find('.last-page') expect(page.text()).toBe('5ページ >>') // 成功した! }) }) })
2度setProps
していてなんかモヤるけど、やりたいことはできた。