detect jest and use http adapter instead of XMLhttpRequest
See original GitHub issueSo I had a peculiar evening. We have an unconventional test suite in Jest. We run it in the regular mode, not with
"testEnvironment": "node"
so it has window.
In one test I was trying to fetch something with axios, but it always broke down and showed me a Network error
.
I was banging my head against the table and had a nice debug session and eventually found out this thread: https://stackoverflow.com/questions/42677387/jest-returns-network-error-when-doing-an-authenticated-request-with-axios
Which was awesome. Using this spectacular hack:
if (process.env.LOOOP_ENVIRONMENT === 'test') {
const path = require('path')
const lib = path.join(
path.dirname(require.resolve('axios')),
'lib/adapters/http'
)
const http = require(lib)
config.adapter = http
}
I was able resolve the problem. What I want to suggest is-since jest is very popular test runner and a lot of people are running jest in regular mode, not in node they will often bang their heads.
Maybe it would be good to detect when we’re running in jest and refrain from using XMLHttpRequest
? Is that too much to ask?
Issue Analytics
- State:
- Created 6 years ago
- Reactions:33
- Comments:10 (1 by maintainers)
I’ve had a fun afternoon too. I solved it by adding
testEnvironment: 'node',
tojest.config.js
file.By default jest runs tests in
jsdom
mode which addsXmlHttpRequest
to global scope which in turns causes axios to think it’s running in a browser and making requests viaXmlHttpRequest
instead of node’s native library.If you need to keep
jsdom
astestEnvironment
(Vue components testing…), here is another nice workaround:Add
global.XMLHttpRequest = undefined
in your Jest setup file.