简体   繁体   中英

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.

[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:

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 ???

You might be having API mock response. So, in your spec file you need to add the mock response for that particular API call.

Include your file in spec file which has your actual backend API call. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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