首页 > 解决方案 > 笑话:ReferenceError:请求未定义

问题描述

即使代码有效,我也无法通过我的笑话测试:

describe("Testing the API call", () => {
  test("Testing the API call", () => {
    sendToServer("Hey there!")
  })
})

开玩笑地向我抛出了这个: ReferenceError: Request is not defined (it can't find Request constructor)

我对玩笑很陌生,所以我只尝试了堆栈溢出时能找到的方法,但没有解决方案。我尝试从 html 导入请求,但没有成功。

标签: apirequestjestjsreferenceerror

解决方案


如果你愿意分享你的getData功能会更容易帮助你,但让我假设你正在做类似的事情来获取你的数据:

async function getUsers() {
  const URL = `https://randomuser.me/api/?results=10`;
  try {
    const response = await fetch(URL);
    return response.json();
  }
  catch (e) {
    console.log(e);
    return {}
  }
}

上面的函数将调用Random User API并返回一个带有结果数组的 Object,在我们的例子中是 10 个随机用户。

为了测试这个功能,你可以编写测试,例如:

  describe('getUsers function', () => {
    test('the data returned is an object', async () => {
     const data = await index.getUsers();
     expect(data).toBeInstanceOf(Object);
  });
    test('the Results array has 10 entries', async () => {
      const data = await index.getUsers();
      expect(data.results.length).toBe(10)
    });
  });

在这里,您将断言,您确实从通话中返回了 Object,并且确实返回了正确数量的通话用户。


推荐阅读