Nock + jest with latest axios

🦋Allegra
1 min readSep 11, 2023

--

Super quick note, but if you’re upgrading to the latest axios(v1.5.0 at the time of writing), this might save you some time.

If you have jest tests written with nock, you probably have this line to set axios default adapter in your jest.setup.js that is now causing an error.

axios.defaults.adapter = require('axios/lib/adapters/http')

ie., Cannot find module ‘axios/lib/adapters/http’ from ‘jest.setup.ts’

The Solution

The solution is to set it to http (since axios no longer expose their http adapter code)

// If you are using jsdom, axios will default to using the XHR adapter which
// can't be intercepted by nock. So, configure axios to use the node adapter.

axios.defaults.adapter = 'http'

and update your jest.config.js by adding a moduleNameWrapper for axios:

 moduleNameMapper: {
// Force CommonJS build for http adapter to be available.
'^axios$': require.resolve('axios'),
}

That is it! Your jest + nock + axios tests should be passing again. Thanks to nock for nicely updated docs https://github.com/nock/nock#axios 🙌🏽

Photo by İbrahim Özdemir on Unsplash

--

--

🦋Allegra
🦋Allegra

No responses yet