Search code examples
reactjsreduxjestjsreact-testing-libraryredux-thunk

Mock redux thunk API call


I'm just trying to make a mock response in my thunk handler, but I can't spot the place I did wrong. I have added some comments in the redux controller to get a clear view. can someone help me to get what I want?

component

const handleRequest = () => {
        setProductSaving(true)

        const callback = (response) => {
            if (response.status === 200) {
                setProductSaving(false)
                setProductRequested(true)
            }
        }

        const productInfo = {
            // product input
        }

        dispatch(requestProduct(productInfo))
    }

Thunk controller

export const requestProduct = ({ smeId, userId, requestPayload, callback, approveeUserId, isApprovee = false}) => {
    return async (dispatch) => {
        
        try {
            let endpointUrl = `/product/${smeId}/user/${userId}`;

            if (isApprovee) {
                endpointUrl = `/product/${smeId}/approver/${userId}?approveeUserId=${approveeUserId}`;
            }

            const response = await axios.put(endpointUrl, requestPayload);
            // NOTE: should mock above response when calling
            // CURRENT => response is 'undefined' here. so below code doesn't run on test environment
            // REQUIRED => to run below code with the mock response

            if(response.status === 200) {
                dispatch({
                    type: NOTIFY_STATUS,
                    payload: {
                        message: response.data.message,
                        variant: 'success',
                    },
                })
            }

            callback?.(response)
            
        } catch (error) {
            dispatch({
                type: NOTIFY_STATUS,
                payload: {
                    message: error.message,
                    variant: 'error',
                },
            })
        }
    }
}

Test file

jest.mock('axios');

test('should be able to request product', () => {
        const { getByTestId } = render( <Router>
            <Provider store={store}>
                <ThemeProvider theme={techpathTheme}>
                    <ProductCard product={product} />
                </ThemeProvider>
            </Provider>
        </Router>)

        fireEvent.click(getByTestId('requestbtn')) // this will trigger the action in component 

        const mockedResponse = {
            data: { message: "SMEProductTagAddedSuccessfully"},
            status: 200,
            statusText: 'OK',
        };

        axios.put.mockResolvedValueOnce(mockedResponse);
    })

Solution

  • You should mock the axios.put before you fire the event. Otherwise it will call the original axios behaviour.

    jest.mock('axios');
    
    test('should be able to request product', () => {
            const mockedResponse = {
                data: { message: "SMEProductTagAddedSuccessfully"},
                status: 200,
                statusText: 'OK',
            };
    
            axios.put.mockResolvedValueOnce(mockedResponse);
    
            const { getByTestId } = render( <Router>
                <Provider store={store}>
                    <ThemeProvider theme={techpathTheme}>
                        <ProductCard product={product} />
                    </ThemeProvider>
                </Provider>
            </Router>)
    
            fireEvent.click(getByTestId('requestbtn')) // this will trigger the action in component 
        })