首页 > 解决方案 > 对 API 的异步请求在 Jest 中返回未定义

问题描述

我对测试很陌生,特别是对 Jest。我正在关注几个教程,它们以我尝试的方式处理异步代码。当我制作一个用虚拟数据解析的自定义 Promise 时,我的代码似乎可以工作。但是当我尝试使用 axios 从外部 API 获取时,Jest 会得到未定义的响应。

// functions2.js
const axios = require("axios")

const fetch = () => {
    axios.get("https://jsonplaceholder.typicode.com/users")
      .then(res => res.data)
      .catch(err => err);
}

module.exports = fetch;
// functions2.test.js

describe("async operation", ()=>{
    it("should be defined", ()=>{
        expect(fetch).toBeDefined()
    }); // Passed

    it("should fetch", async () => {
        expect.assertions(1);
        const data = await fetch();
        expect(data).toBeTruthy();
    }) // Did not pass, data is undefined

    it("should fetch, using promises", () => {
        expect.assertions(1);
        return fetch().then(data => {
        expect(data).toBeTruthy();
        })  // Did not pass, got 0 assertions
    })
})

在一个教程中,我遇到这与通过 Node.JS 运行的 Jest 有关,但我不知道如何处理它,因为我不知道 node.js。

此外,我遵循 Traversy Media 的教程,克隆了他的 Git 存储库(https://github.com/bradtraversy/jest_testing_basics)并遇到了同样的问题(尽管在视频中它有效)

标签: jestjs

解决方案


问题是因为您没有从fetch.

将您的更新functions2.js为:

const fetch = async () => {
  return axios
    .get("https://jsonplaceholder.typicode.com/users")
    .then(res => res.data)
    .catch(err => err);
};

希望能帮助到你。


推荐阅读