I am trying to test a async/await function which does an api call using axios to get users. I am new to testing React applications and using JEST (trying first time), unable to get the test running.
I have tried using mock function in JEST. My Code is as follows:
// component --users
export default class Users extends React.Component {
constructor(props) {
super(props);
this.state = {};
this.getUsers = this.getUsers.bind(this);
}
/*does an api request to get the users*/
/*async await used to handle the asynchronous behaviour*/
async getUsers() {
// Promise is resolved and value is inside of the resp const.
try {
const resp = await axios.get(
"https://jsonplaceholder.typicode.com/users"
);
if (resp.status === 200) {
const users = resp.data;
/* mapped user data to just get id and username*/
const userdata = users.map(user => {
var userObj = {};
userObj["id"] = user.id;
userObj["username"] = user.username;
return userObj;
});
return userdata;
}
} catch (err) {
console.error(err);
}
}
componentDidMount() {
this.getUsers().then(users => this.setState({ users: users }));
}
/*****************************************************************/
//props(userid ,username) are passed so that api call is made for
//getting posts of s psrticular user .
/*****************************************************************/
render() {
if (!this.state.users) {
return (
<div className="usersWrapper">
<img className="loading" src="/loading.gif" alt="Loading.." />
</div>
);
}
return (
<div className="usersWrapper">
{this.state.users.map(user => (
<div key={user.id}>
<Posts username={user.username} userid={user.id} />
</div>
))}
</div>
);
}
}
//axios.js-mockaxios
export default {
get: jest.fn(() => Promise.resolve({ data: {} }))
};
//users.test.js
describe("Users", () => {
describe("componentDidMount", () => {
it("sets the state componentDidMount", async () => {
mockAxios.get.mockImplementationOnce(
() =>
Promise.resolve({
users: [
{
id: 1,
username: "Bret"
}
]
}) //promise
);
const renderedComponent = await shallow(<Users />);
await renderedComponent.update();
expect(renderedComponent.find("users").length).toEqual(1);
});
});
});
the test fails -
FAIL src/components/users.test.js (7.437s) ● Users › componentDidMount › sets the state componentDidMount
expect(received).toEqual(expected)
Expected value to equal: 1 Received: 0
Please help me figure out the problem. i am totally new to testing reactapps
getUsers
is called, and does not show your test assertion. Is there acomponentDidMount
method that you left out? Or does your test callgetUsers
directly? What happens if you remove thetry
/catch
? – Jesse Hallettshallow
is not an async method, you don't needawait
before it. It looks like test is finished earlier then component is re-rendered after got users, can you checksetTimeout( () => expect(renderedComponent.find("users").length).toEqual(1), 0)
(in the very end of your test)? – Alex