1

I recently upgraded redux-api-middleware from 2.3.0 to 3.0.1 When running my tests with jest@22.2.1 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.

josemigallas
  • 3,761
  • 1
  • 29
  • 68

2 Answers2

0

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');

alex
  • 2,036
  • 2
  • 16
  • 19
  • But i didn't need that in 2.3.0 :/ did something happened? – josemigallas Jan 09 '19 at 10:03
  • Something must have changed. I didn't dig into it, just found how to fix it. – alex Jan 10 '19 at 19:59
  • Looks like it works without installing that package, simply by mocking global.fetch. Do you know of any bad consequence of this? I will gladly accept your answer if you could elaborate a bit more. – josemigallas Jan 15 '19 at 11:49
  • There shouldn't be any issues. I use [fetch-mock](https://www.npmjs.com/package/fetch-mock) in all my tests, and I think it does exactly that - mock global fetch. – alex Jan 17 '19 at 00:35
  • What I did is simply add `global.fetch = () => {}` to my `global-mocks.js`, in case you want to include it in your answer, just a suggestion :) Maybe I need a better mock in the future but for now it works like a charm. – josemigallas Jan 17 '19 at 08:17
0

Use createMiddleware with your own fetch compilant function

https://github.com/agraboso/redux-api-middleware#createmiddlewareoptions

iamandrewluca
  • 3,411
  • 1
  • 31
  • 38