Search code examples
reduxjestjsredux-api-middleware

redux-api-middleware throws fetch is not defined


I recently upgraded redux-api-middleware from 2.3.0 to 3.0.1 When running my tests with [email protected] I get this ReferenceError:

ReferenceError: fetch is not defined

  19 | export function sortPolicyChain (payload: Array<ChainPolicy>): SortPolicyChainAction {
  20 |   return { type: 'SORT_POLICY_CHAIN', payload }
> 21 | }
  22 |
  23 | export type UpdatePolicyInChainAction = { type: 'UPDATE_POLICY_IN_CHAIN', policyConfig: ChainPolicy }
  24 | export function updatePolicyInChain (policyConfig: ChainPolicy): UpdatePolicyInChainAction {

  at Object.<anonymous> (node_modules/redux-api-middleware/lib/index.cjs.js:404:3)
  at Object.<anonymous> (app/javascript/src/Policies/actions/PolicyChain.jsx:21:27)
  at Object.<anonymous> (spec/javascripts/Policies/actions/PolicyChain.spec.jsx:3:20)

The stacktrace points to this line in PolicyChain.jsx:

export function fetchChain (serviceId: string): RSSAAction {
  return {
    [RSAA]: {
      endpoint: `/admin/api/services/${serviceId}/proxy/policies.json`,
      method: 'GET',
      credentials: 'same-origin',
      types: [REQUEST, SUCCESS, FAILURE]
    }
  }
}

According to the documentation here:

If provided, the fetch option must be a function that conforms to the Fetch API. Otherwise, the global fetch will be used.

But it looks like the global fetch can't be found. Any ideas?

Codebase can be found in github.


Solution

  • This happens because Jest runs inside of Node.js, which doesn't have a global fetch(). You can fix this by installing isomorphic-fetch and adding this to your Jest setupFiles:

    require('isomorphic-fetch');