Very Useful JavaScript Methods to Simplify Your API Test Validation

* A Photo By Ekrem Kurt

In this article, I will try to cover the most useful JavaScript methods to make testing not only more fun, but also more flexible to produce more scenarios. Basic test cases will be demonstrated in Postman, however, they can be easily adapted to any similar JS Test Frameworks such as Cypress, TestCafé, or WebDriverIO… etc.

For this tutorial, we are going to use an open-source API, which can be found here: “https://www.metaweather.com/api/”.

Let’s start with giving our URL with the query parameter:

https://www.metaweather.com/api/location/search/?query=em

If we run the above URL, then we can get the following response body.

Before starting testing, we store the response body in a variable.

const jsonData = pm.response.json();

You have received an array containing multiple objects — each one representing a city, including title, woeid (Where On Earth IDentifier), and latitude_longitude info.

First, we want to make sure that location_type is City for all the objects.

Let’s say you need an array containing only the woeid of each city. There are multiple ways to achieve this. You might want to do it by creating an empty array, then using .forEach(), .for(...of), or a simple .for() to meet your goal. But I think the easiest way is to use .map().

.map()

const woeiIds = jsonData.map(woei => woei.woeid);

With just one line code, we have saved all “woeIDs” in a variable as an array. So how does .map() work? The callback runs for each value in the array and returns each new value in the resulting array.

We can then easily verify our array:

pm.test("Verify existing of the woeid in the list", () => {
pm.expect(woeiIds[0]).to.be.oneOf([2449323,641142, 680564, 13383]);
pm.expect(woeiIds[3]).to.be.oneOf([2449323,641142, 680564, 13383]);
});

Let’s say we need to verify the total woeid number. With .reduce(), it’s pretty straightforward.

.reduce()

const totalWoeiIds = jsonData.reduce((acc, woei) => acc + woei.woeid, 0);// Result: totalWoeiIds: "3784412"

Just like .map(), .reduce() also runs a callback for each element of an array. What’s different here is that reduce passes the result of this callback (the accumulator) from one array element to the other. Starting value is set as 0, it can be set as desired. Again, just with one line code, we could get the result.

pm.test("Verify the total number of the woeiIds", () => {
pm.expect(totalWoeiIds).to.eql(3784412);});

What if you have an array, but only want some elements in it? That’s here .filter() might be very useful.

.filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

const cityBremen = jsonData.filter(city => city.title ==("Bremen"));

Here is the result: We can now work with only one object, and make any validation we want.

pm.test("Verify the city title", () => {
pm.expect(cityBremen).to.be.an("array");
pm.expect(cityBremen[0].title).to.eql("Bremen");});

Similarly, if we need only the cities, whose woeid’s greater than 650000.

function isGreater(element) {return (element >= 650000);}let testElements = woeiIds.filter(isGreater);// Result: (2) [2449323, 680564]

You want to know if there are any cities with latt_long property. There are many ways to achieve that goal. However, the shortest way would be the using some method.

.some()

some() executes the function once for each element in the array — If it finds an array element where the function returns a true value, some() returns true and does not check the remaining values. Otherwise, it returns false.

const checkFirstCity = jsonData.some(coord => coord.latt_long);// Result: true

We could then verify the result.

pm.test("Verify whether there are cities with latt_long property", () => {pm.expect(checkFirstCity).to.eql(true);});

In the same way, we could get the first matched result by using .find(). The logic is the same, instead of getting true or false as an answer, we get the object itself.

.find()

The find() method returns the value of the array element that passes a test (provided by a function). .find() will return the first match, and does not check the remaining values. If more values match your condition, it won’t matter. Only the first match will be returned.

const firstCity = jsonData.find(coordinate => coordinate.latt_long);// Result: {title: "Memphis", location_type: "City", woeid: 2449323…}

As we can see, we could get the first city, which has latt_long property. Even though all cities have this property, we only get the first true match as a result. Again verify the result.

pm.test("Verify the first city with latt_long property", () => {
pm.expect(firstCity.title).to.eql("Memphis");
pm.expect(firstCity.location_type).to.eql("City");
});

Overall Testing

As we see, even though the response body is a relatively very simple one, with the help of some useful methods we have produced different test scenarios. It is not limited to what is here described, can be of course extended to more scenarios. Overall test results can also be seen as follows:

Conclusion

Using the above-mentioned JS Methods instead of common loops like .for or .forEach() not only makes your code shorter, but also more understandable. While writing test cases, it will make your job easier, and gives you more flexibility to produce more scenarios. So, don’t hesitate to use these very useful methods.

☕️ Happy testing! ☕️

You can follow me on Medium for more articles, connect with me on LinkedIn

These articles you might like as well.

Sources:

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store