Logo

dev-resources.site

for different kinds of informations.

Test-Driven Development (TDD) in Front-end.

Published at
11/8/2024
Categories
webdev
javascript
unittest
programming
Author
jayd007
Author
7 person written this
jayd007
open
Test-Driven Development (TDD) in Front-end.

Test-Driven Development (TDD) is widely recognized for improving code quality and reducing bugs in software development. While TDD is common in back-end and API development, it’s equally powerful in front-end development. By writing tests before implementing features, front-end developers can catch issues early, ensure consistent user experiences, and refactor confidently. In this article, we'll explore TDD in the context of front-end development, discuss its benefits, and walk through examples using React and JavaScript.

Why Use TDD in Frontend Development?

Frontend development has unique challenges, including user interactions, rendering components, and managing asynchronous data flows. TDD helps by enabling developers to validate their logic, components, and UI states at every stage. Benefits of TDD in frontend include:

Higher Code Quality: Writing tests first encourages clean, maintainable code by enforcing modularity.

Improved Developer Confidence: Tests catch errors before code reaches production, reducing regression bugs.

Better User Experience: TDD ensures components and interactions work as intended, resulting in smoother UX.

Refactoring Safety: Tests provide a safety net, allowing developers to refactor without fear of breaking features.

How TDD Works in Frontend: The Red-Green-Refactor Cycle

The TDD process follows a simple three-step cycle: Red, Green, Refactor.

Red - Write a test for a new feature or functionality. This test should initially fail since no code is implemented yet.

Green - Write the minimum code needed to pass the test.
Refactor - Clean up and optimize the code without changing its behavior, ensuring that the test continues to pass.

Let’s apply TDD with an example of building a simple search component in React.

Example: Implementing TDD for a Search Component in React
Step 1: Setting Up Your Testing Environment

To follow along, you’ll need:

React for creating the UI components.
Jest and React Testing Library for writing and running tests.

# Install dependencies
npx create-react-app tdd-search-component
cd tdd-search-component
npm install @testing-library/react

Enter fullscreen mode Exit fullscreen mode

Step 2: Red Phase – Writing the Failing Test

Let’s say we want to build a Search component that filters a list of items based on user input. We’ll start by writing a test that checks if the component correctly filters items.

// Search.test.js
import { render, screen, fireEvent } from "@testing-library/react";
import Search from "./Search";

test("filters items based on the search query", () => {
  const items = ["apple", "banana", "cherry"];
  render(<Search items={items} />);

  // Ensure all items are rendered initially
  items.forEach(item => {
    expect(screen.getByText(item)).toBeInTheDocument();
  });

  // Type in the search box
  fireEvent.change(screen.getByRole("textbox"), { target: { value: "a" } });

  // Check that only items containing "a" are displayed
  expect(screen.getByText("apple")).toBeInTheDocument();
  expect(screen.getByText("banana")).toBeInTheDocument();
  expect(screen.queryByText("cherry")).not.toBeInTheDocument();
});

Enter fullscreen mode Exit fullscreen mode

Here’s what we’re doing:

Rendering the Search component with an array of items.
Simulating typing "a" into the search box.
Asserting that only the filtered items are displayed.

Running the test now will result in a failure because we haven’t implemented the Search component yet. This is the “Red” phase.

Step 3: Green Phase – Writing the Minimum Code to Pass the Test

Now, let’s create the Search component and write the minimal code needed to make the test pass.

// Search.js
import React, { useState } from "react";

function Search({ items }) {
  const [query, setQuery] = useState("");

  const filteredItems = items.filter(item =>
    item.toLowerCase().includes(query.toLowerCase())
  );

  return (
    <div>
      <input
        type="text"
        placeholder="Search..."
        value={query}
        onChange={(e) => setQuery(e.target.value)}
      />
      <ul>
        {filteredItems.map((item) => (
          <li key={item}>{item}</li>
        ))}
      </ul>
    </div>
  );
}

export default Search;

Enter fullscreen mode Exit fullscreen mode

In this code:

We use useState to store the search query.
We filter the items array based on the query.
We render only the items that match the query.

Now, running the test should result in a “Green” phase with the test passing.

Step 4: Refactor – Improving Code Structure and Readability

With the test passing, we can focus on improving code quality. A small refactor might involve extracting the filtering logic into a separate function to make the component more modular.

// Refactored Search.js
import React, { useState } from "react";

function filterItems(items, query) {
  return items.filter(item =>
    item.toLowerCase().includes(query.toLowerCase())
  );
}

function Search({ items }) {
  const [query, setQuery] = useState("");
  const filteredItems = filterItems(items, query);

  return (
    <div>
      <input
        type="text"
        placeholder="Search..."
        value={query}
        onChange={(e) => setQuery(e.target.value)}
      />
      <ul>
        {filteredItems.map((item) => (
          <li key={item}>{item}</li>
        ))}
      </ul>
    </div>
  );
}

export default Search;

Enter fullscreen mode Exit fullscreen mode

With the refactor, the code is cleaner, and the filtering logic is more reusable. Running the test ensures the component still behaves as expected.

TDD for Handling Edge Cases

In TDD, it’s crucial to account for edge cases. Here, we can add tests to handle cases like an empty items array or a search term that doesn’t match any items.
Example: Testing Edge Cases

test("displays no items if the search query doesn't match any items", () => {
  const items = ["apple", "banana", "cherry"];
  render(<Search items={items} />);

  // Type a query that doesn't match any items
  fireEvent.change(screen.getByRole("textbox"), { target: { value: "z" } });

  // Verify no items are displayed
  items.forEach(item => {
    expect(screen.queryByText(item)).not.toBeInTheDocument();
  });
});

test("renders correctly with an empty items array", () => {
  render(<Search items={[]} />);

  // Expect no list items to be displayed
  expect(screen.queryByRole("listitem")).not.toBeInTheDocument();
});

Enter fullscreen mode Exit fullscreen mode

These tests further ensure that our component handles unusual scenarios without breaking.

TDD in Asynchronous Frontend Code

Frontend applications often rely on asynchronous actions, such as fetching data from an API. TDD can be applied here as well, though it requires handling asynchronous behavior in tests.
Example: Testing an Asynchronous Search Component

Suppose our search component fetches data from an API instead of receiving it as a prop.

// AsyncSearch.js
import React, { useState, useEffect } from "react";

function AsyncSearch() {
  const [query, setQuery] = useState("");
  const [items, setItems] = useState([]);

  useEffect(() => {
    async function fetchData() {
      const response = await fetch(`https://api.example.com/search?q=${query}`);
      const data = await response.json();
      setItems(data);
    }
    if (query) fetchData();
  }, [query]);

  return (
    <div>
      <input
        type="text"
        placeholder="Search..."
        value={query}
        onChange={(e) => setQuery(e.target.value)}
      />
      <ul>
        {items.map((item) => (
          <li key={item}>{item}</li>
        ))}
      </ul>
    </div>
  );
}

export default AsyncSearch;

Enter fullscreen mode Exit fullscreen mode

In testing, we can use jest.fn() to mock the API response.

import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import AsyncSearch from "./AsyncSearch";

global.fetch = jest.fn(() =>
  Promise.resolve({
    json: () => Promise.resolve(["apple", "banana"]),
  })
);

test("fetches and displays items based on the search query", async () => {
  render(<AsyncSearch />);

  fireEvent.change(screen.getByRole("textbox"), { target: { value: "a" } });

  // Wait for the items to be fetched and rendered
  await waitFor(() => {
    expect(screen.getByText("apple")).toBeInTheDocument();
    expect(screen.getByText("banana")).toBeInTheDocument();
  });
});

Enter fullscreen mode Exit fullscreen mode

Best Practices for TDD in Front-end

Start Small: Focus on a small piece of functionality and gradually add complexity.
Write Clear Tests: Tests should be easy to understand and directly related to functionality.
Test User Interactions: Validate user inputs, clicks, and other interactions.
Cover Edge Cases: Ensure the application handles unusual inputs or states gracefully.
Mock APIs for Async Tests: Mock API calls to avoid dependency on external services during testing.

Conclusion

Test-Driven Development brings numerous advantages to front-end development, including higher code quality, reduced bugs, and improved confidence. While TDD requires a shift in mindset and discipline, it becomes a valuable skill, especially when handling complex user interactions and asynchronous data flows. Following the TDD process—Red, Green, Refactor—and gradually integrating it into your workflow will help you create more reliable, maintainable, and user-friendly front-end applications.

unittest Article's
30 articles in total
Favicon
Getting Started with Android Testing: Building Reliable Apps with Confidence (Part 1/3)
Favicon
What is the Order of Importance for Unit, Integration, and Acceptance Tests in Software Development?
Favicon
Top 17 Best Unit Testing Tools
Favicon
JUnit Testing: A Comprehensive Guide to Unit Testing in Java
Favicon
Crafting Effective Unit Tests for Generative AI Applications
Favicon
Harder, Better, Faster, Stronger Tests With Fixtures
Favicon
How To Test Your JavaScript Application With Jest Framework?
Favicon
Effective Strategies for Writing Unit Tests with External Dependencies like Databases and APIs
Favicon
Debugging Laravel Routes in Testing
Favicon
Is Unit Test really a MUST?
Favicon
Let's Learn Unit Testing in Python with pytest! 🚀
Favicon
An opinionated testing approach for VueJS
Favicon
PHP: Should I mock or should I go?
Favicon
Implementing Unit Testing in ReadmeGenie
Favicon
8.Angular Unit Testing: A Step-by-Step Approach
Favicon
“Why Unit Testing Is Not an Option, But a Duty”
Favicon
Early Raises $5M to Transform Software Development
Favicon
Smth about Unittests
Favicon
Unit Testing in Laravel: A Practical Approach for Developers
Favicon
Assert with Grace: Custom Soft Assertions using AssertJ for Cleaner Code
Favicon
Writing Integration And Unit Tests for a Simple Fast API application using Pytest
Favicon
End-To-End Testing for Java+React Applications
Favicon
Writing XUnit Tests without Object Arrays
Favicon
Comprehensive Testing in .NET 8: Using Moq and In-Memory Databases
Favicon
Test-Driven Development (TDD) in Front-end.
Favicon
Unit testing
Favicon
jUnit - Testes unitários em Java
Favicon
Testing Spring Boot Applications: Unit, Integration, and Mocking — A Comprehensive Guide
Favicon
Let’s Make Jest Run Much Faster
Favicon
Test-Driven Development

Featured ones: