【问题标题】:Async Request to API return undefined in Jest对 API 的异步请求在 Jest 中返回未定义
【发布时间】:2019-08-24 00:06:42
【问题描述】:

我对测试很陌生,尤其是 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
    })
})

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

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

【问题讨论】:

    标签: jestjs


    【解决方案1】:

    问题是因为您没有返回来自fetch 的承诺。

    将您的 functions2.js 更新为:

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

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 2020-06-14
      • 2018-03-22
      • 2018-08-09
      • 2019-06-18
      • 2018-04-30
      • 1970-01-01
      • 2021-09-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多