简体   繁体   中英

JS Jest Mocking - expected received undefined error

I have code that uses axios to get some data.

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.

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. 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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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