はじめに
通常、ストアのモックはファイル上部の jest.mock で定義することが多いですが、「特定のテストケース(it ブロック)の時だけ、ストアの値を変更して挙動を確認したい」という場面があります。
課題
以下のように、モジュールレベル(ファイルの先頭)で jest.mock を使ってストアをモックしている場合、すべてのテストケースで同じモックデータが使われてしまいます。
import { mount } from '@vue/test-utils';
import MyComponent from '@/components/MyComponent.vue';
// ファイル全体で共通のモックになってしまう
jest.mock('@/stores/user', () => ({
useUserStore: () => ({
name: '通常 太郎',
isAdmin: false
})
}));
describe('MyComponent.vue', () => {
it('デフォルトの状態が表示されること', () => {
const wrapper = mount(MyComponent);
// ...テストコード
});
it('管理者ユーザーの場合のみ、特別なボタンが表示されること', () => {
// ここでだけ isAdmin を true にしたいが、上の jest.mock が効いているため難しい
});
});
解決策
@pinia/testing パッケージが提供する createTestingPinia を利用します。
これを使うと、mount 時のプラグイン設定として initialState を渡すことができ、テストケースごとにストアの状態を定義し直すことが可能です。
実装例
特定のテストケース内だけで、Pinia の状態を定義してコンポーネントをマウントします。
import { mount } from '@vue/test-utils';
import { createTestingPinia } from '@pinia/testing';
import MyComponent from '@/components/MyComponent.vue';
describe('MyComponent.vue', () => {
it('特定のテストケースだけ、Storeの値を上書きする', async () => {
// 1. テスト用の Pinia インスタンスを作成
const pinia = createTestingPinia({
stubActions: false, // アクションを実際に実行させたい場合は false
createSpy: jest.fn, // spy の作成関数を指定
initialState: {
// 'storeのID': { 上書きしたい状態 }
'user': {
profile: {
name: 'テスト ユーザー',
isAdmin: true
}
}
}
});
// 2. 作成した pinia を global.plugins に渡してマウント
const wrapper = mount(MyComponent, {
global: {
plugins: [pinia]
}
});
// 3. 検証
// ストアの値に基づいた表示が行われているか確認
const nameLabel = wrapper.find('.user-name');
expect(nameLabel.text()).toBe('テスト ユーザー');
const adminBadge = wrapper.find('.admin-badge');
expect(adminBadge.exists()).toBe(true);
});
});
環境
- Vue.js:
3.2.45 - Pinia:
2.0.28 - @pinia/testing:
0.0.14 - jest:
26.6.3 - @vue/test-utils:
2.2.6