0

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")

Moon
  • 790
  • 1
  • 8
  • 19
  • 1
    `fetch-mock` package mocks http requests made using `fetch`. But you are using `axios`, why don't you use `maxios`? – Lin Du May 01 '21 at 05:29
  • Thanks @slideshowp2, I just find the document of fetch-mock and it says 'Mock http requests made using fetch.`. Don't know it's fetch spec before. – Moon May 03 '21 at 05:57

0 Answers0