5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

JESTでよく使うVueのMockの方法まとめ[Nuxt]

Last updated at Posted at 2021-09-21

概要

テストを楽に行うためにMockの仕方を調べることが多かった
以下は個人的によく利用したMockの方法をまとめたものとなる

目次

  1. methodsはWrapperの上書きをする
  2. $routerはconfig.mock
  3. VuexのSotreはshallowMountに設定
  4. 外部ツールはjest.spyOn

環境

"nuxt": "^2.0.0",
"vue": "^2.6.11",
"vuetify": "^2.2.27",
"jest": "^26.6.3",
"playwright": "^1.10.0",

Mock方法

methodsはWrapperの上書きをする

  • mountまたはshallowMountでWrapperを生成し、Wrapperのmethodを上書きする
  • 全てのテストでmock状態にしたい場合はbeforeEachを使う
  • mock関数色々 https://jestjs.io/ja/docs/mock-function-api

テストしたいページ: ~/pages/index.vue

<script>
export default {
  methods: {
    getString() {
        return 'test1';
    },
  },
};
</script>

テストコード

import page from '~/pages/index.vue';
beforeEach(() => {
  const store = new Vuex.Store({getters});
  wrapper = shallowMount(page, {store});
  // Methodの上書き
  wrapper.vm.getString = jest.fn().mockReturnValue('test2');
});
afterEach(() => {
  wrapper = null; // test毎リセットしておくと安全
});
describe('Methods', () => {
  test('login: validationエラーの場合', async () => {
    const result = wrapper.vm.getString();
    await flushPromises();
    expect(result).toBe('test2');
  });
});

$routerはconfig.mock

import {config} from '@vue/test-utils';
beforeEach(() => {
  config.mocks['$router'] = {
    push: jest.fn(),
    go: jest.fn(),
    currentRoute: {
      path: 'dummy_path',
    },
  };
});

VuexのStoreはshallowMountに設定

getters.js (とか actions.js)

const getters = {
  'test/getter': jest.fn().mockReturnValue(''),
};
export default getters;

store.test.js

import Vuex from 'vuex';
import getters from 'getters.js';
import actions from 'actions.js';
let wrapper;

beforeEach(() => {
  const store = new Vuex.Store({getters, actions});
  wrapper = shallowMount(page, {store});
});

外部ツールはjest.spyOnを使う

import Auth from '@aws-amplify/auth';
beforeEach(() => {
  // currentAuthenticatedUser はMockしたい関数名
  jest.spyOn(Auth, 'currentAuthenticatedUser').mockResolvedValue({data: ''});
});
5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?