Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create-react-app: use a proxy for Jest tests

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!

like image 884
Marnix.hoh Avatar asked Apr 23 '26 09:04

Marnix.hoh


1 Answers

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

like image 118
Marnix.hoh Avatar answered Apr 27 '26 19:04

Marnix.hoh



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!