如何在Reactjs中使用Jest测试Axios.all和Axios.spread

时间:2020-04-09 07:20:34

标签: reactjs jestjs axios

我将为以下方法编写JEST测试用例

const ApiSearchAddressCodeAndPostalCode = store => next => action => {
    const {
        type,
        txtAdd,
        sortAddressCode
    } = action;

    // Param Of Api Postal Code Search
    const requestBodyPostalCode = {
        postalCode: postalCode,
    };

    const headersPostalCode = {
        'Content-Type': 'application/json',
        'x-api': apiKey
    };

    return Axios.all([
        Axios.get(
            `${SEARCH_BASE_ADD_URL}/${txtAdd}`,
            { headers: { 'x-api': apiKey } },
            {
                params: {
                    sort: sortAddressCode,
                }
            }
        ),
        //API SEARCH POSTAL CODE - (POST)
        Axios.post(
            SEARCH_BASE_POSTAL_NAME_URL,
            requestBodyPostalCode,
            { headers: headersPostalCode }
        )
    ])
    .then(
        Axios.spread(function(addressCode, postalCode) {
           data.resultItem = addressCode.data.resultItem.concat(
               postalCode.data.resultItem
           );
        }

它使用axios.all和axios.spread取回数据。.i已为Axios.get和Axios.post编写了简单的测试用例。但是如何为此编写测试用例?

我试图写如下。

it('Check handle call api success', async () => {
    const mockAxiosSpreadResult = jest.fn();
    axios.all.mockResolvedValue("test");
    axios.spread.mockReturnValue(mockAxiosSpreadResult);
    await ApiSearchAddressCodeAndPostalCode(store)(next)(action);
    expect(mockAxiosSpreadResult).toHaveBeenCalledWith("test");
}

0 个答案:

没有答案