gpt4 book ai didi

javascript - JS Jest Mocking - 预期收到未定义的错误

转载 作者:行者123 更新时间:2023-12-03 00:16:33 26 4
gpt4 key购买 nike

我有使用 axios 获取一些数据的代码。

const axios = require('axios');

class Users {
static async all() {
let res = await axios.get('http://localhost:3000/users');
return res.data;
}
}

module.exports = Users;

这应该使用 Jest 框架进行测试。

const axios = require('axios');
const Users = require('./users');

jest.mock('axios');

test('should fetch users', () => {

const users = [{
"id": 1,
"first_name": "Robert",
"last_name": "Schwartz",
"email": "rob23@gmail.com"
}, {
"id": 2,
"first_name": "Lucy",
"last_name": "Ballmer",
"email": "lucyb56@gmail.com"
}];

const resp = { data : users };

// axios.get.mockResolvedValue(resp);
axios.get.mockImplementation(() => Promise.resolve(resp));

// console.log(resp.data);

return Users.all().then(resp => expect(resp.data).toEqual(users));
});

测试失败并显示

expect(received).toEqual(expected)

Expected: [{"email": "rob23@gmail.com", "first_name": "Robert", "id": 1, "last_name": "Schwartz"}, {"email": "lucyb56@gmail.com", "first_name": "Lucy", "id": 2, "last_name": "Ballmer"}]
Received: undefined

真实数据是:

{ "users": [
{
"id": 1,
"first_name": "Robert",
"last_name": "Schwartz",
"email": "rob23@gmail.com"
},
{
"id": 2,
"first_name": "Lucy",
"last_name": "Ballmer",
"email": "lucyb56@gmail.com"
}
...
]
}

我在想这可能是命名/未命名 JSON 数组的问题。如何解决?

最佳答案

看起来这只是一个简单的错误。

您正在返回resp.data来自Users.all()所以不要检查 resp.data在你的expect只需检查resp :

return Users.all().then(resp => expect(resp).toEqual(users));  // SUCCESS

关于javascript - JS Jest Mocking - 预期收到未定义的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54512880/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com