Reputation: 11637
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": "[email protected]"
}, {
"id": 2,
"first_name": "Lucy",
"last_name": "Ballmer",
"email": "[email protected]"
}];
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": "[email protected]", "first_name": "Robert", "id": 1, "last_name": "Schwartz"}, {"email": "[email protected]", "first_name": "Lucy", "id": 2, "last_name": "Ballmer"}]
Received: undefined
The real data is:
{ "users": [
{
"id": 1,
"first_name": "Robert",
"last_name": "Schwartz",
"email": "[email protected]"
},
{
"id": 2,
"first_name": "Lucy",
"last_name": "Ballmer",
"email": "[email protected]"
}
...
]
}
I was thinking maybe this is a problem with named/not named JSON arrays. How to fix it?
Upvotes: 0
Views: 9034
Reputation: 45780
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
Upvotes: 1