やりたいこと
specファイルからmock APIを叩いて想定通りにstore.stateに値が格納されているか確認したい
使用ライブラリ
・axios-mock-adapter(モック)
現状
stateの中身が空
ソース
スペックファイル
callApi
を叩いて結果がstateに格納されているかテストしようとしています。
call
1import MockAdapter from 'axios-mock-adapter' 2import axios from 'axios' 3import Vuex from 'vuex' 4import { createLocalVue } from '@vue/test-utils' 5import { cloneDeep } from 'lodash' 6import { actions, mutations } from '../../store/api/call.js' 7import CERTIFY_INFO from '../../plugins/mockData/certify/certifyInfo' 8 9const state = { 10 api: {} 11} 12 13// beforeEachで毎回Storeを生成するために。 14const initStore = () => { 15 return cloneDeep({ 16 state, 17 mutations, 18 actions 19 }) 20} 21 22describe('callApiModule/actions', () => { 23 // eslint-disable-next-line no-unused-vars 24 let store 25 let localVue 26 beforeEach(() => { 27 // eslint-disable-next-line prefer-const 28 localVue = createLocalVue() 29 localVue.use(Vuex) 30 // eslint-disable-next-line prefer-const 31 store = new Vuex.Store(initStore()) 32 }) 33 34 const mock = new MockAdapter(axios) 35 afterEach(() => { 36 mock.reset() 37 }) 38 39 mock.onPost('/api/call').reply(200, CERTIFY_INFO) 40 41 describe('callApiModule/actions', () => { 42 it('call action', async () => { 43 const commit = jest.fn() 44 45 // await actions.callApi({ commit }) 46 await store.dispatch('api/call/callApi') 47 expect(store.state.api).toBe(CERTIFY_INFO.result) 48 }) 49 }) 50})
callApi
export const actions = { async callApi (context) { const res = await this.$axios.$post('/api/call') context.commit('setResult', res) } }
モックAPI
import MockAdapter from 'axios-mock-adapter' import CERTIFY_INFO from './mockData/certify/certifyInfo' export default ({ app, $axios }) => { const mock = new MockAdapter($axios, { delayResponse: 500 }) mock.onPost('/api/call').reply((config) => { const certifyInfo = CERTIFY_INFO return [200, certifyInfo.result] }) mock.onAny().passThrough() }
通常の処理(テストじゃなく)については想定の結果が得られております。
テストではaxiosそのものは呼べないからaxiosをモック化する必要がある??
- ↑の方法は現在調査中です。
jestについてあまり経験がないのでご指摘があれば幸いです。
あなたの回答
tips
プレビュー