Unit test and mocking axios
If you want to check how to call external api's using axios then check here.
So if we are using axios then it becomes very important as to how to write unit test. Because unit test is very important if we talk about in development life cycle, it gives developers a wide knowledge about how the code behaves in certain inputs.
This way developers can test their code and be confident that in all the cases the code is working fine and we can deploy the code to server.
Now that we have developed that unit test is important then the question is how to write unit test for axios calls or external API calls.
index.js
const axios = require('axios');
// Mocking the axios
jest.mock('axios');
// it() or test()
axios.mockResolvedValueOnce('test');
There are many cases where there are multiple api calls in single stretch then in that case.
axios.mockResolvedValueOnce('test1').mockResolvedValueOnce('test2');
In this case, the first axios call will return test1 and the second api call will return test2.
This is how you can mock axios in unit test.
No comments:
Post a Comment
If you have any doubts, Please let me know