DEV Community

Cover image for Unit & Integration Testing
Jorjis Hasan
Jorjis Hasan

Posted on

1

Unit & Integration Testing

🔥 Fireup Unit and Integration Testing with Jest and Axios

Testing is a vital part of ensuring that your code works as expected and remains reliable over time. This guide explains Unit Testing and Integration Testing with examples using Jest and Axios. By the end of this, you’ll be equipped to write your own tests confidently! 🚀


🗂️ Table of Contents

  1. Introduction to Testing
  2. Unit Testing
  3. Integration Testing with Axios
  4. Conclusion

📚 Introduction to Testing

Testing involves verifying that your code behaves as expected under various conditions. With Jest, a popular testing library, you can write two key types of tests:

  • Unit Tests: Test individual functions or components in isolation.
  • Integration Tests: Verify how different parts of your application work together.

These tests help catch bugs early, reduce regression issues, and maintain high code quality. Let’s start by exploring Unit Testing! 🧪


🧪 Unit Testing

Unit Testing focuses on testing individual functions or components in isolation. It ensures each small unit of your code works independently as intended.

Example: Testing a Sum Function

Here’s a simple function that sums two numbers:

// src/sum.js
export const sum = (a, b) => a + b;
Enter fullscreen mode Exit fullscreen mode

Writing the Unit Test

Create a test file src/__tests__/sum.test.js and write the following:

// src/__tests__/sum.test.js
import { sum } from '../sum';

describe('sum', () => {
  it('should add two numbers correctly', () => {
    expect(sum(1, 2)).toBe(3);
    expect(sum(-1, 1)).toBe(0);
  });
});
Enter fullscreen mode Exit fullscreen mode

Running the Unit Test

Run the test with the following command:

npx jest src/__tests__/sum.test.js
Enter fullscreen mode Exit fullscreen mode

If everything works as expected, you’ll see a ✅ confirming that the test passed.

Integration Test Passing Screenshot


🔗 Integration Testing with Axios

Integration Testing ensures that different parts of your application work well together. Let’s test a function that fetches user data from an API using Axios.

Example: Fetching User Data

Suppose we have a function that retrieves user data from an API:

// src/apiService.js
import axios from 'axios';

export const fetchUserData = async (userId) => {
  const response = await axios.get(`https://jsonplaceholder.typicode.com/users/${userId}`);
  return response.data;
};
Enter fullscreen mode Exit fullscreen mode

Writing the Integration Test

To test this function, create a file src/__tests__/apiService.test.js. We’ll mock Axios to prevent real API calls.

// src/__tests__/apiService.test.js
import axios from 'axios';
import { fetchUserData } from '../apiService';

jest.mock('axios'); // Mocking Axios globally for tests

describe('fetchUserData', () => {
  it('should fetch user data successfully', async () => {
    const mockUserData = { id: 1, name: 'Alice' };
    axios.get.mockResolvedValue({ data: mockUserData });

    const userData = await fetchUserData(1);

    expect(userData).toEqual(mockUserData);
    expect(axios.get).toHaveBeenCalledWith('https://jsonplaceholder.typicode.com/users/1');
  });

  it('should throw an error if fetching fails', async () => {
    axios.get.mockRejectedValue(new Error('Fetch failed'));

    await expect(fetchUserData(1)).rejects.toThrow('Fetch failed');
  });
});
Enter fullscreen mode Exit fullscreen mode

Key Points:

  • jest.mock('axios'): Mocks the entire Axios library.
  • mockResolvedValue: Simulates a successful API response.
  • mockRejectedValue: Simulates an API failure.

Running the Integration Test

Run the test with the following command:

npx jest src/__tests__/apiService.test.js
Enter fullscreen mode Exit fullscreen mode

If successful, Jest will confirm the tests for both success and failure scenarios have passed. ✅

Integration Test Passing Screenshot

🎉 Conclusion

Unit and Integration Testing are essential tools for building reliable and maintainable applications. By using Jest and Axios, you can:

  • Validate individual functions with Unit Tests.
  • Verify interactions between modules with Integration Tests.

Unit and Integration Testing are powerful methods to ensure your code works well individually and collectively. Start adding tests to your codebase today and enjoy the peace of mind that comes with knowing your application is well-tested. Happy coding and testing! 🧑‍💻✨

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay