【问题标题】:JavaScript Jest Testing Using fetch() and getting 'Undefined' from JSON dataJavaScript Jest 测试使用 fetch() 并从 JSON 数据中获取“未定义”
【发布时间】:2021-02-09 12:38:44
【问题描述】:

我正在学习使用 jest 进行 fetch 和 javascript 测试。我遇到了以下问题并尝试解决但失败了:

我正在尝试验证来自 https://reqres.in/api/users/1 的 JSON 中的一些数据,使用 JavaScript Jest 测试通过 fetch() 从 JSON 中获取数据。但它返回失败(另见截图):

expect(received).toEqual(expected)    // deep equality
Expected: "George"
Received: undefined

来自https://reqres.in/api/users/1的JSON数据:

data:
  id    1
  email "george.bluth@reqres.in"
  first_name    "George"
  last_name "Bluth"
  avatar "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg"

这是我所做的:

我创建了一个user.js 文件,它有一个名为fetchData() 的函数来从https://reqres.in/api/users/1 获取数据。 fetchData() 代码:

function fetchData(){
    return fetch('https://reqres.in/api/users/1')
              .then(response => response.json());
});

我还创建了一个user.test.js 测试文件:

const fetchData = require('./user');
test('Verify first name', () => {
    return fetchData().then(data => {
    expect(data.first_name).toEqual('George');
    });
});

当我运行测试 (npx jest user.test.js) 时,它返回失败并显示如上所示的结果。测试应该通过,因为名字的 JSON 数据与预期的字符串“George”匹配。我认为这里的问题是 JSON 返回的数据在某种程度上是不正确的,所以它说未定义。我应该如何更正我的代码?

我尝试了多种方法来修复此错误,包括使用 JSON.stringify 和 JSON.parse 返回 JSON 数据以便与预期的字符串进行比较,但均未成功。我在这一点上不确定我做错了什么。有人可以帮我指出为什么它说 undefine 吗?

非常感谢您的帮助。

【问题讨论】:

  • 请恢复上次的编辑,你杀死了格式。

标签: javascript json jestjs fetch


【解决方案1】:

回复是:

{
  "data": {
    "id": 1,
    "email": "george.bluth@reqres.in",
    "first_name": "George",
    "last_name": "Bluth",
    "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg"
  },
  "ad": {
    "company": "StatusCode Weekly",
    "url": "http://statuscode.org/",
    "text": "A weekly newsletter focusing on software development, infrastructure, the server, performance, and the stack end of things."
  }
}

响应中有data键,所以应该是:

test('Verify first name', () => {
    return fetchData().then(data => {
        expect(data.data.first_name).toEqual('George');
    });
});

【讨论】:

  • 解决了!!非常感谢埃斯图斯。现在它返回了通行证,应该是。但是你能向我解释一下为什么在 data.data.first_name 中有一个额外的数据吗?
猜你喜欢
  • 2018-07-08
  • 2023-01-26
  • 1970-01-01
  • 1970-01-01
  • 2018-01-29
  • 1970-01-01
  • 2021-04-24
  • 1970-01-01
  • 2016-06-23
相关资源
最近更新 更多