简体   繁体   English

JS开玩笑嘲笑-预期收到未定义的错误

[英]JS Jest Mocking - expected received undefined error

I have code that uses axios to get some data. 我有使用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;

This should be tested with Jest framework. 这应该使用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));
});

The test fails with 测试失败

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

The real data is: 实际数据是:

{ "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"
    }
...
]
}

I was thinking maybe this is a problem with named/not named JSON arrays. 我在想这可能是命名/未命名JSON数组的问题。 How to fix it? 如何解决?

Looks like it's just a simple mistake. 看起来这只是一个简单的错误。

You are returning resp.data from Users.all() so instead of checking resp.data in your expect just check resp : 您正在从Users.all()返回resp.data ,所以resp.data检查您expect resp.dataresp.data检查resp

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM