Jestでaxiosの処理をモック化する
概要
Jestでaxiosの処理をモック化する方法。
モック化の方法
テスト対象の関数(axiosGetTest, axiosPostTestData)
<template> <div> <div>{{ axiosGetTestData }}</div> <div>{{ axiosPostTestData }}</div> </div> </template> <script lang="ts"> import { Component, Vue } from 'nuxt-property-decorator'; @Component({}) export default class extends Vue { private axiosGetTestData: string = ''; private axiosPostTestData: string = ''; private async axiosGetTest(): Promise<any> { const response = await this.$axios.get('エンドポイント'); this.axiosGetTestData = response.data.status; } private async axiosPostTestData(): Promise<any> { const response = await this.$axios.post('エンドポイント'); this.axiosPostTestData = response.data.status; } } </script>
テストコード
import 任意の名前1 '@/pages/ファイル名'; describe('任意の名前2', () => { it('任意の名前3', () => { const thisVal = { $axios: { get(): Promise<any> { return new Promise((resolve, reject) => { resolve({ data: { status: 'getOk' } }); }); } }, axiosGetTestData: '' }; await 任意の名前1.options.methods.axiosGetTest.call(thisVal); expect(thisVal.axiosGetTestData).toEqual('getOk'); }); it('任意の名前4', () => { const thisVal = { $axios: { post(): Promise<any> { return new Promise((resolve, reject) => { resolve({ data: { status: 'postOk' } }); }); } }, axiosPostTestData: '' }; await 任意の名前1.options.methods.axiosPostTestData.call(thisVal); expect(thisVal.axiosPostTestData).toEqual('postOk'); }); });