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?
Using Node 18.15.0 I was able to do the following without any third-party lib:
import assert from 'node:assert'
import { describe, it, mock } from 'node:test'
describe('Class', () => {
    it('fetch stuff', async () => {
        const json = () => { 
            return {
                key: 'value'
            }
        }
        mock.method(global, 'fetch', () => {
            return { json, status: 200 }
        })
        const response = await fetch()
        assert.strictEqual(response.status, 200)
        const responseJson = await response.json()
        assert.strictEqual(responseJson.key, 'value')
        mock.reset()
    })
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With