Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I mock Node.js fetch HTTP requests/responses in Node 18?

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?

like image 375
Glynn Bird Avatar asked Oct 28 '25 03:10

Glynn Bird


1 Answers

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()
    })
})
like image 111
jotafeldmann Avatar answered Oct 30 '25 23:10

jotafeldmann



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!