如何在 Node 18 中模拟 Node.js 获取 HTTP 请求/响应?

Gly*_*ird 3 http mocking fetch node.js nock

我正在使用新的(从版本 18 开始)Node.js“fetch”API 来执行 HTTP 请求,例如

const response = await fetch(SOMEURL)
const json = await response.json()
Run Code Online (Sandbox Code Playgroud)

这可行,但我想“模拟”这些 HTTP 请求,以便我可以进行一些自动化测试并能够模拟一些 HTTP 响应以查看我的代码是否正常工作。

通常我会使用优秀的nock包和 Axios 来模拟 HTTP 请求,但它似乎不适用于fetchNode 18。

fetch那么在 Node.js 中使用时如何模拟 HTTP 请求和响应呢?

jot*_*ann 13

使用Node 18.15.0,我无需任何第三方库即可执行以下操作:

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()
    })
})
Run Code Online (Sandbox Code Playgroud)