Search code examples
javascriptreduxjest-fetch-mock

Using FetchMock to mock fetch not working


Im trying to mock a fetch request to confirm if the right actions were dispatched: the redux function:

export function loginRequest(email, password) {
  return (dispatch) => {
    dispatch(login(email, password))
    return fetch('http://localhost:8000/login-success.json')
      .then((response) => response.json())
      .then((response) => dispatch(loginSuccess()))
      .catch((error)=>dispatch(loginFailure()))
  }
}

the test:

test("API returns the right response, the store received two actions LOGIN and LOGGING_SUCCESS", () => {
  const store = mockStore({})
  fetchMock.get('*', {})

  
  return store.dispatch(loginRequest('jack', 124)).then(()=>{
    const actions = store.getActions()
    console.log(actions)
    expect(actions).toEqual([login('jack', 124), loginSuccess()])
  })
})

the console.log output:

   [
      { type: 'LOGIN', user: { email: 'jack', password: 124 } },
      { type: 'LOGIN_FAILURE' }
    ]

im expecting the second action to be LOGIN_SUCCESS action instead. it seems like the mock isnt working at all. Am i missing something here


Solution

  • SOLVED: in the file where i defined the loginRequest function, i was importing fetch (import fetch from 'node-fetch';) hence calling the function in the test resulted in an actual fetch call rather than fetch-mock