API Testing with Jest & Axios
In the previous course, we utilized Postman to perform API testing. However, that was from the perspective of Manual Testing.
In Automation Testing, to effectively perform API testing, we would require some kind of a JavaScript method which enables us to make HTTP requests through code.
Axios is a perfect choice in this scenario. It is a Node.JS library which allows us to programmatically make API requests.
The two methods which we will be looking at are:
js9123axios.get(url[, config]);axios.post(url, data[, config]);
The usage of these methods is demonstrated in the following video:
- , opens subtitles settings dialogsubtitles settings
- subtitles off
- , selectedEnglish Captions
- 2x
- 1.5x
- , selected1x
- 0.5x
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
For-example, we can make a GET request to the api/posts
endpoint using the following code:
js912axios.get('http://localhost:3000/api/posts');
The HTTP Request methods return a response
object containing all the data of the HTTP response. We can use the await
key for the method to return that object and store it in a variable:
js912const response = await axios.get('http://localhost:3000/api/posts');
Since we are using await
, we need to enclose the code inside an async
function:
js91234async function exampleFunction() {const response = await axios.get('http://localhost:3000/api/posts');}
From the response, we can extract the Status Code of the response using the status
attribute of the response object. The response data can be extracted from the data
attribute of the response object.
js91234const res = await axios.get('http://localhost:3000/api/posts');console.log(res.status); // Status Codeconsole.log(res.data); // Response Data
It's imperative to enclose the code inside a try-catch block to make sure the program does not crash in case the HTTP request fails - since the get
and post
methods raise exceptions in case of request failure.
The post
method can be used for making a POST request. The usage is very similar to a GET request:
js9912345678910async function exampleFunction() {try {const res = await axios.get('http://localhost:3000/api/posts');console.log(res.status);console.log(res.data);} catch(err) {console.log(err);}}
1. What is Axios, and why is it used in Automation Testing for API testing?
2. Which of the following is a correct way to make a GET request using Axios?
Дякуємо за ваш відгук!
Запитати АІ
Запитати АІ
Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат