banner

KuchBhiLearning - A free website to learn and code

This is a good learning site. This contains details of cloud computing, AWS, AWS-CDK, AWS-SDK codes and examples including S3, Redis, lambda, api-gateway, cloudfront, cloudformation.

 Unit test and mocking axios


Unit test and mocking axios jest -

Axios is widely popular in node js bubble and many of the projects are using axios as their primary package for calling external api's.

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

Copyright 2022, KuchBhiLearning - A free website to learn and code. All rights Reserved.
| Designed by Yaseen Shariff