【问题标题】:Why do I get reference error for fetch when I do unit tests using Jest?当我使用 Jest 进行单元测试时,为什么会出现获取参考错误?
【发布时间】:2022-02-18 18:54:15
【问题描述】:

我是使用 Jest 进行单元测试的新手,但基本上我有一个文件 client.js,如下所示:

function add(a, b) {
    return a + b;
}
const fetcher = () => {

    return fetch('http://localhost:3000/').then(res => res.json);
}


module.exports = {add, fetcher};

client.test.js如下:



const client = require('../client');

test('Testing addition', () => {
    expect(client.add(1, 2)).toBe(3);
});

test('Yet another addition', () => {
    expect(client.add(3, 10)).toBe(13);
});



test('Testing a promise', () => {
    return client.fetcher().then(data => {
        expect(data).toBe(1824);
    })
});

当我尝试运行测试时,它会抛出错误ReferenceError: fetch is not defined。我该如何解决这个问题?

【问题讨论】:

  • 您无法在服务器上测试客户端代码。 fetch 只存在于浏览器环境中。
  • 注意是res => res.json()
  • @ChrisG 那么我应该使用什么框架来进行客户端的单元测试呢?

标签: javascript node.js jestjs


【解决方案1】:

要么:

  • 在某处定义 fetch 函数(例如,通过加载 NPM 上可用的节点获取模块)
  • 在运行 Node 时使用 --experimental-fetch 标志(并确保它是版本 17.5 or newer

【讨论】:

  • @CupOfGreenTea — 如果您使用 Node.js 运行它,则不会。
  • 奇怪的是,我在使用 --experimental-fetch 时遇到了开箱即用的问题,似乎 Jest 覆盖了全局变量,我无法访问 fetch() / Response / Request 等 - 我能够通过将它们注入jest.config.js - globals: { fetch, Response, Request } 来解决 - 感觉很脏 - 但我认为在一两个月内其他人会正确修复它!
猜你喜欢
  • 1970-01-01
  • 2016-01-19
  • 2015-10-23
  • 2020-02-25
  • 2021-05-07
  • 2023-03-12
  • 2019-10-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多