LoginSignup
0
0

More than 1 year has passed since last update.

VitestによってVueコンポーネント中のAxiosをテスト

Posted at

1.Vitestをインストール

公式サイトに参照

yarn add -D vitest

vue-test-utilsをインストールしなければ、インストール

yarn add -D @vue/test-utils

2.使用

テストファイルにて
例えば、テストしたいVueコンポーネントをmountedすると/api/v1/testpostリクエストをします

import { test, expect, vi } from 'vitest'
import { mount } from '@vue/test-utils'
import Components from '@/components/Components.vue'

// リクエストのレスポンス、モックデータ
const result = { message: 'data取得成功' }

test('test', async (): Promise<void> => {
    // axiosを監視して、レスポンスのモックデータを設定
    const spyPost = await vi.spyOn(axios, 'post').mockResolvedValue(result)
    // テストしたいVueコンポーネントを使う
    const wrapper = await mount(Components
    // リクエストパラメータのモックデータ                      
    const params = { id: '1'}
    // postリクエストをモックして検証
    expect(axios.post).toHaveBeenCalledWith('/api/v1/test', params)
    // リクエストのレスポンスを検証
    expect(await axios.post().then(res => res)).toBe(result)
    // axios監視をクリア
    spyPost.mockRestore()
})
0
0
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
0
0