Asynchronous code testing of React-app

Kunvar singh
3 min readAug 1, 2021

--

Here I’ll guide to you guy’s, how to do test react-app asynchronous code. I’m hoping that you have an basic idea about how to write the basic test cases, if not then please have a look at my previous article here, that’s pretty much simple. If you guy’s are familiar about the asynchronous code execution.
There are several ways to achieve this as explained below :

1. Promise :
In this below example, I have made a simple function that return promise to us for finding the specific user in the given array.

promise.js

Below is the test case for the above written promise based function :

promise.spec.js

Below is the expected output when you run “npm test — promise.spec.js” on your vs code terminal :

expected output

2. API Endpoint :
Here we will make an simple axios api call to fetch some user data via open source/free api service. And will write test cases about the same.

api.js

below is the test cases for above async/await based fetchingUsers function:

api.spec.js

You can run the below commands on you terminal : “npm test — api.spec.js”

expected outcome

3. CallBack :
Here we have made a simple multiplication function, which takes 2 argument (i.e number and callback function), once this will done their complete task then it will call the callback function (i.e cb).

function callbackBasedFunc(number, cb) {
cb(number * 2);
}

Below is the test case for callback based test function : In this example we have to pass the done argument for the test block function, so that jest can be notified that once callback function API testing will be completed. And we have also made and one local function that will help us to send the same function as an argument to receive the callback data on it. Try to run the below code in the same way and you will get your expected outcome.

describe("Async Code Test cases::", () => {
test(“to check multiplication once callback finish:”, (done) => {
function callback(data) {
expect(data).toEqual(4);
done();
}
callbackBasedFunc(2, callback);
});
});

If you enjoyed reading this article and learned something new, please don’t forget

to leave a clap or two, or three… 👏👏👏
THANK YOU.

--

--

Kunvar singh

Technology evanglist, keen to learn new things in a day.