In this tutorial, we aim to demonstrate how to test REST APIs using Postman and Jest.
You will learn:
Prerequisites:
Firstly, we will start with Jest. Jest is a JavaScript testing framework maintained by Facebook. It's great for testing JavaScript and React applications.
Install Jest
You can install Jest using npm (node package manager) with the following command:
npm install --save-dev jest
Writing a Test
In Jest, each test is written as a function which takes a name and a function containing the logic for the test.
test('test name', function() {
// test logic here
})
Postman
Postman is a platform that allows us to test, develop and document APIs. It provides a user-friendly interface to send HTTP requests and view responses.
Sending a Request
To send a request in Postman:
You can add query parameters, headers, and body data as needed.
Example 1: Simple Jest Test
// Import the http module
const http = require('http');
// Import the jest-fetch-mock module
const fetchMock = require('jest-fetch-mock');
// Enable fetch mocks
fetchMock.enableMocks();
// Test
test('checks if Jest works', () => {
expect(1).toBe(1);
});
// Test API
test('User fetch successful', async () => {
fetchMock.mockOnce(JSON.stringify({ name: 'John' }));
const response = await fetch('/users/1');
const user = await response.json();
expect(user).toEqual({ name: 'John' });
});
In the above example, we first test if Jest works by checking if 1 is equal to 1. Then we mock a fetch request and check if it returns the correct data.
Example 2: Sending a Request in Postman
Let's say you have a GET request for 'http://localhost:3000/users/1'.
In the response section, you should see the user data returned from the server.
In this tutorial, we learned how to install and write tests using Jest. We also learned how to send requests to an API using Postman.
Next, you should learn more about different types of testing like unit testing, integration testing, and end-to-end testing. You should also learn more about different HTTP methods and status codes.
Here are some resources for further reading:
Exercise 1:
Write a test for a function that adds two numbers.
Solution:
test('adds 1 + 2 to equal 3', () => {
function add(a, b) {
return a + b;
}
expect(add(1, 2)).toBe(3);
});
Exercise 2:
Send a POST request in Postman to 'http://localhost:3000/users' with the following body data:
{
"name": "John",
"email": "john@example.com"
}
Solution:
For further practice, try writing more complex tests and sending different types of requests in Postman.