【问题标题】:JS Jest Mocking - expected received undefined errorJS Jest Mocking - 预期收到未定义的错误
【发布时间】:2019-06-28 00:01:36
【问题描述】:

我的代码使用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 数组的问题。 如何解决?

【问题讨论】:

  • mockImplentation() 函数未实现

标签: javascript unit-testing mocking jestjs jest-mock-axios


【解决方案1】:

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

您从Users.all() 返回resp.data,所以不要在expect 中检查resp.data,只需检查resp

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-05
    • 2020-09-15
    • 1970-01-01
    • 2021-12-24
    • 2017-11-12
    • 2011-07-11
    • 2023-01-26
    • 2017-06-15
    相关资源
    最近更新 更多