Redux Jest test fetchMock.getOnce not working

515 Views Asked by At

I'm using Redux, fetchMock, redux-mock-store to write a redux action test. Based on this document, https://redux.js.org/recipes/writing-tests, I write my one, but it seems the fetchMock is not working. The get request on the redux action uses the original value instead of fetchMock data.

Can anyone let me know where is wrong?

actions:

import { types } from "./types"
import axios from "axios"
import { getPosts } from "../apis"
export const fetchPosts = () => (dispatch) => {
    return getPosts()
        .then((res) => {
            dispatch({
                type: types.GET_POSTS,
                payload: res.data
            })
        })
        .catch((err) => {
            // console.log(err);
        })
}

test:

import moxios from "moxios"
import { testStore } from "./../../Utils"
import { fetchPosts } from "./../actions"
import configureMockStore from "redux-mock-store"
import thunk from "redux-thunk"
import fetchMock from "fetch-mock"
import { types } from "../actions/types"

const middlewares = [thunk]
const mockStore = configureMockStore(middlewares)

describe("select_actions", () => {
    afterEach(() => {
        fetchMock.restore()
    })

    it("Dispatches the correct action and payload", () => {
        const expectedState = [
            {
                title: "Example title 1",
                body: "Some Text"
            },
            {
                title: "Example title 2",
                body: "Some Text"
            },
            {
                title: "Example title 3",
                body: "Some Text"
            }
        ]
        const store = mockStore({})

        fetchMock.getOnce("https://jsonplaceholder.typicode.com/posts?_limit=10", {
            body: expectedState,
            headers: { "content-type": "application/json" }
        })

        const expectedActions = [{ type: types.GET_POSTS, payload: expectedState }]

        return store.dispatch(fetchPosts()).then(() => {
            expect(store.getActions()).toEqual(expectedActions)
        })
    })
})

API:

import axios from "axios"
export const getPosts = async () => await axios.get("https://jsonplaceholder.typicode.com/posts?_limit=10")

0

There are 0 best solutions below