3

I want to use an actual API for my react Jest tests. Because the test environment is JSDom, I can't make cross-origin requests. In development this is easily solved by specifying a proxy in the package.json file, however this does not apply to the test suite run through: npm test.

I know that it is possible to specify a proxy when creating a new JSDom instance using (see docs):

const resourceLoader = new jsdom.ResourceLoader({
  proxy: "http://127.0.0.1:9001",
});

Now I can't find a way to use this with my application, which is created using create-react-app (CRA)... So my question is, is there some way to specify a proxy when running Jest through a CRA app?

Thanks!

Pang
  • 9,564
  • 146
  • 81
  • 122
Marnix.hoh
  • 1,556
  • 1
  • 15
  • 26

1 Answers1

7

I just found out how to do this. There is a Jest configuration option that sets the url of the JSDom instance: "testURL". However, it won't work when specifying it in package.json like:

jest: {
    "testURL": "http://localhost:4000"
}

What does work is specifying the option directly in the NPM script. This would make the NPM test script look like:

"test": "react-scripts test --testURL=http://localhost:4000"

Hope it helps someone with the same issue

Marnix.hoh
  • 1,556
  • 1
  • 15
  • 26