简体   繁体   English

我如何测试 vuex 动作,它带有 jest 里面有一个 api 调用?

[英]How can I test vuex action which with jest which has an api call inside it?

ASYNC ACTION VUEX : This is async action which will be called from the component, it consists of an function fetchGaragesData that will make an api call to fetch data from server. ASYNC ACTION VUEX :这是将从组件调用的异步操作,它由一个函数 fetchGaragesData 组成,该函数将进行 api 调用以从服务器获取数据。

[ACTION_TYPES.FETCH_CASHLESS_GARAGES]: async (
        { dispatch, commit, state, rootState },
        payload
    ) => {
        commit(MUTATION_TYPES.SET_MISC_KEYS, {
            fetchingCashlessGaragesInitiated: true,
        })
        let { insurerSlug, makeId, rtoCode } = payload
        const url = ApiUrls.getCashlessGarages + `${insurerSlug}/${makeId}`
        const response = await fetchGaragesData(url, rtoCode)
        dispatch(ACTION_TYPES.MODIFY_RTO_WISE_GARAGES_DATA, response)
    },

IMPLEMENTATION OF fetchGaragesData: this function internally calls axios get: fetchGaragesData 的实现:这个函数在内部调用 axios get:

export const fetchGaragesData = (url: string, rtoCode: string) => {
    return get(url, {
        rto_code: rtoCode,
        all_states_data: true,
    })
}

How can I test action ACTION_TYPES.FETCH_CASHLESS_GARAGES ???如何测试操作 ACTION_TYPES.FETCH_CASHLESS_GARAGES ???

You might be having API mock response.您可能有 API 模拟响应。 So, in your spec file you need to add the mock response for that particular API call.因此,在您的规范文件中,您需要为该特定 API 调用添加模拟响应。

Include your file in spec file which has your actual backend API call.将您的文件包含在具有实际后端 API 调用的规范文件中。 For example:例如:

import someName from 'path of file'

jest.mock('someName', () => ({
 fetchGaragesData: jest.fn((url, rtoCode) =>
  success({ body: 
    Here comes your response body
 }})
)

url and rtoCode should be the name of the variables used in your API call file. url 和 rtoCode 应该是 API 调用文件中使用的变量的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM