什么是嘲笑一个只能与开玩笑在浏览器中运行的获取调用的最简单方法?

发布于 2025-02-06 14:28:07 字数 539 浏览 2 评论 0原文

如果我正在测试一个函数的函数,并且我在项目中使用的所有获取呼叫都只能在浏览器中运行。我是否仍然需要在节点上安装一些软件包并导入它以模拟该调用?

像这样的简单场景参考:在开玩笑的测试中未定义未定义:

// fetcKey.js

export async function fetchKey() {
    try {

        const key = await fetch('http://localhost:3000/key');
        return (await key.text());
    }
    catch(error){
        throw error;
    }
}

//fetchKey.test.js

import fetchKey from './fetchKey'

test('Checks fetchKey return', () => {

    expect(fetchKey()).not.toThrow();

})

If I'm testing a function that makes a fetch call, and all the fetch calls I have in the project are only meant to run in the browser. Do I still need to have some package installed on node and import it to be able to mock that fetch call?

A simple scenario like this throws ReferenceError: fetch is not defined in the Jest test:

// fetcKey.js

export async function fetchKey() {
    try {

        const key = await fetch('http://localhost:3000/key');
        return (await key.text());
    }
    catch(error){
        throw error;
    }
}

//fetchKey.test.js

import fetchKey from './fetchKey'

test('Checks fetchKey return', () => {

    expect(fetchKey()).not.toThrow();

})

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

海夕 2025-02-13 14:28:08

您应该能够使用 node> nodefetch

import fetch from 'node-fetch';

((请注意,这是一个eCmascript模块,不能用需要导入,如其文档中所述)。

You should be able to use node-fetch:

import fetch from 'node-fetch';

(Note it's an ECMAScript Module and cannot be imported with require, as mentioned in their documentation).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文