I am using the new (as of version 18) Node.js "fetch" API to perform HTTP requests e.g.
const response = await fetch(SOMEURL)
const json = await response.json()
This works, but I want to "mock" those HTTP requests so that I can do some automated testing and be able to simulate some HTTP responses to see if my code works correctly.
Normally I have used the excellent nock package alongside Axios to mock HTTP requests, but it doesn't appear to work with fetch in Node 18.
So how can I mock HTTP requests and responses when using fetch in Node.js?
Node 18's
fetchfunction isn't built on the Node.js http module like most HTTP libraries (including Axios, request etc) - it's a total rewrite of an HTTP client built on the lower-level "net" library called undici. As such, "nock" cannot intercept requests made from thefetchfunction (I believe the team are looking to fix this, but at the time of writing, Nock 13.2.9, Nock does not work forfetchrequests).The solution is to use a MockAgent that is built into the undici package.
Let's say your code looks like this:
This code makes a real HTTP request to a CouchDB server running on localhost.
To mock this request, we need to add
undiciinto our project:and add some code to intercept the request:
The above code now has its HTTP "fetch" request intercepted with mocked response.