关于前端:使用vitest测试vue组件中的axios

7次阅读

共计 644 个字符,预计需要花费 2 分钟才能阅读完成。

1. 装置 Vitest

参考官网

yarn add -D vitest

如果没有装置vue-test-utils

yarn add -D @vue/test-utils

2. 应用

在测试用例中,假如组件挂起就会向 /api/v1/test 发动 post 申请

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