Monday, February 1, 2021

how to fix " ReferenceError: fetch is not defined" in redux testing with nock and jest?

when i implemented a test a case against the API call to test the reducer, we can use NOCK to mock the API with JEST test run.

here is the sample code for the above test case.

import { createStoreapplyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import nock from 'nock'

import { fetchUser } from '../../src/actions'
import usersReducer from '../../src/reducers/users'

// global.fetch = require('node-fetch');
const middlewares = [ thunk ]
let store

beforeEach(() => {
  store = createStore(usersReducerapplyMiddleware(thunk))
})

afterEach(() => {
  nock.cleanAll()
})

test('initial state should be empty array (no users)', () => {
  expect(store.getState()).toEqual([])
})

test('fetchUser action should add user object to state', () => {
  const username = 'dan'
  const realname = 'Dan Deng'
  const userObj = { username:usernamerealname:realname }
  console.log(userObj)
  nock('http://localhost:8080/')
    .get(`/api/users/${username}`)
    .reply(200userObj)

  expect.assertions(1)

  const action = fetchUser(username)
  return store.dispatch(action)
    .then(() =>
      expect(store.getState()).toContainEqual(userObj)
    )
})


however i ran the test case with JEST, the following error came immediately. since i use fetch function from fetch-node module.

 ● fetchUser action should add user object to state

    ReferenceError: fetch is not defined

      23 |     types:[FETCH_USER_REQUEST, FETCH_USER_SUCCESS, FETCH_USER_FAILURE],
      24 |     promise: fetch(`http://localhost:8080/api/users/${username}`)
    > 25 |     .then(response=>response.json())
         |      ^
      26 | })
      27 |
      28 | export const createUser=(username, realname, password)=>thunkCreator({

      at fetchUser (src/actions/users.js:25:6)
      at Object.<anonymous> (_test_/reducers/users.test.js:88:18)

  ● fetchUser action should add user object to state

    expect.assertions(1)

    Expected one assertion to be called but received zero assertion calls.

      84 |     .reply(200, userObj)
      85 |
    > 86 |   expect.assertions(1)
         |          ^
      87 |
      88 |   const action = fetchUser(username)
      89 |   return store.dispatch(action)

      at Object.<anonymous> (_test_/reducers/users.test.js:86:10)


the fix is very easy, we just have to add the reference to fetch in the test file. the test case was passed and succeed.

 global.fetch = require('node-fetch');


No comments:

Post a Comment