Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CORS error - Error: Cross origin http://localhost forbidden - in ReactJS/Jest test only

I'm running into a problem where the request I am making to an outside API is working fine in execution, but when runing a Jest/Enzyme test it gives me a CORS error. The function in question is using a JsonRpc implementation from an API, and using fetch from node-fetch. Not sure if there are settings for CORS I can apply somewhere?

I tried many variations of async waits in Jest/Enzyme testing framework but am still running into issues.

test("it should do something", done => {
    const component = shallow(<CustomComponent />)
    component.instance().customAsyncFunction( result => {
      expect(result.length).toEqual(5)
      done()
    })
    // return component.instance().customAsyncFunction().then(data => {
    //   expect(data.length).toEqual(5)
    // })
  })

I tried the above and a few other methods (like setTimeout and awaiting it) and get the CORS error.

The results I'm getting are:

 console.error
 node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/virtual-console.js:29
   Error: Cross origin http://localhost forbidden
       at dispatchError (...\node_modules\jest-environment-jsdom\node_modules\jsdom\lib\jsdom\living\xhr-utils.js:65:19)
       at Request.client.on.res (...\node_modules\jest-environment-jsdom\node_modules\jsdom\lib\jsdom\living\xmlhttprequest.js:679:38)
       at Request.emit (events.js:198:13)
       at Request.onRequestResponse (...\node_modules\request\request.js:1066:10)
       at ClientRequest.emit (events.js:203:15)
       at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:556:21)
       at HTTPParser.parserOnHeadersComplete (_http_common.js:109:17)
       at TLSSocket.socketOnData (_http_client.js:442:20) undefined

Any ideas?

like image 387
Daniel Avatar asked Dec 05 '25 11:12

Daniel


2 Answers

Jest allows you to set a setup script file. This file will be required before everything else and gives you a chance to modify the environment in which the tests will run. This way you can unset XMLHttpRequest before axios is loaded and the adapter type evaluated since imports are hoisted. Link:https://facebook.github.io/jest/docs/configuration.html#setuptestframeworkscriptfile-string

In package.json

{
  ...,
  "jest": {
    ...,
    "setupTestFrameworkScriptFile": "./__tests__/setup.js",
    ...
  },
  ...
}
__tests__/setup.js

global.XMLHttpRequest = undefined;
like image 185
Aravind Avatar answered Dec 07 '25 10:12

Aravind


The error happens because the external API you call during the tests has a CORS restriction different than Jest's default jsdom one has (http://localhost).

To fix this for Jest v24 - v27 you have to set the appropriate testURL (see the docs) in your Jest config (e.g. jest.config.js):

{
    // Other config values here ...
    "testURL": "http://localhost:8080"
}

In testURL you have to put the actual URL allowed by CORS at your remote API side.

Since v28 the option is organized differentlty via testEnvironmentOptions that requires different update in Jest config.

like image 34
Valentine Shi Avatar answered Dec 07 '25 10:12

Valentine Shi



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!