Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting ReferenceError: fetch is not defined

In my Saga test for my react native application (that does work correctly) I have added the following test that calls a function that perform a POST http call (doScan).

describe('Scan the product and register the scanning action', () => {
  const it = sagaHelper(scanProductSaga(scanProductAction(item)));

  it('logscan via ASL', (result) => {
    expect(result).toEqual(cps(ASLogger.logScan, xxx));
    return logScanResult;
  });

  it('should register the product', (result) => {
    expect(result).toEqual(call(doScan, logScanResult));
  });
});

Separate file:

const doScan = scanObj =>
  toJSON(fetch('https://xxxx.xxxxxx.com/logger/scans', {
    method: 'POST',
    headers: new Headers(CONTENT_TYPE_HEADERS),
    body: JSON.stringify(scanObj),
  }));

Note: the fetch function is from 'react-native-interfaces.js' within the react-native library. The test fails and the error is caused by the following exception :

ReferenceError: fetch is not defined
      at doScan (/Users/andy/WebstormProjects/ASAP/api/index.js:81:11)....

What can cause such issue? What the solution may be?

like image 881
Anto Avatar asked Oct 18 '25 07:10

Anto


1 Answers

react-native has fetch default, but test environment on node.js does not have fetch.

You can import fetch like following at the top of test code.

const fetch = require('node-fetch')

The file react-native-interface.js only declare the type of fetch.

declare var fetch: any;
like image 82
set0gut1 Avatar answered Oct 19 '25 23:10

set0gut1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!