Write Unit Test Case for API call (Fetch) in Nodejs
I
n this article, we will learn how to write unit test cases to test the API call or how we can write the unit
test cases
to test the fetch function (API call). Sometime writing unit test cases of API call is kind of huddle for
programmers,
here we will learn how we can write test case to test API call.
Here we have a code snipet, which contain a method saveExpress(), and in this method we
have an API call (POST request) with some data in body.
Folder structure:
test ->index.ts
test -> index.test.ts
index.ts:
This note is regarding import { fetch, generateToken } from '../utils';
we have two method 'fetch' and 'generateToken' in our utils.
fetch is used to make an API call. generateToken is used to get the generated token.
Don't get confused about these methods.
Now, we need to write the unit test case to test the method saveExpress(), basically, we need to test the API call. So here we'll write our unite test case to test the API (fetch) call.
Let's write unit test case to test the API call:
we'll use Jest to write our unit test case.index.test.ts:
So, you can see we have wrote the test case to test the fetch (API call) in in nodejs.
In this we have ensured that, we are calling our API with the correct endpoint, correct data etc.
Strongly Recommended Books For You:
Reading books opens the door to allow in more lights, If we want to know a man of rare intellect, try to know what books he/she reads.For India:
For Other Countries (United States, United Kingdom, Spain, Italy, Germany, France, Canada, etc)
Thank you
I appreciate you taking the time to read this article. The more that you read, the more things you will know. The more that you learn, the more places you'll go.
If you’re interested in Node.js or JavaScript this link will help you a lot.
If you found this article is helpful, then please share this article's link to your friends to whom this is required, you can share this to your technical social media groups also.
You can follow us on our social media page for more updates and latest article updates.
To read more about the technologies, Please
subscribe us, You'll get the monthly newsletter having all the published
article of the last month.