1. Why We Test Our Application?

  • Ensure Functionality: Verify that the application works as intended and meets the requirements.
  • Catch Bugs Early: Identify and fix issues before they reach production.
  • Improve Code Quality: Encourage better coding practices and design.
  • Facilitate Refactoring: Make changes to the codebase with confidence that existing functionality is preserved.
  • Document Behavior: Serve as documentation for how the code should behave.

2. Manual Testing

Involves manually executing test cases without the use of automation tools. Testers interact with the application, follow test scripts, and check if the application behaves as expected.

Pros: Good for exploratory testing, usability testing, and small-scale projects.

Cons: Time-consuming, error-prone, and less effective for repetitive tasks.

3. Types of Testing

Unit Testing: Tests individual components or functions in isolation to ensure they work as expected.

  • Tools: Jest, Mocha, Jasmine
  • Example: Testing a function that calculates the sum of two numbers.

Integration Testing: Tests how different parts of the application work together. It verifies interactions between components, modules, or services.

  • Tools: Jest, Mocha, Cypress
  • Example: Testing if a component correctly fetches and displays data from an API.

End-to-End Testing: Tests the application as a whole, from the user’s perspective, to ensure that the entire system works together correctly.

  • Tools: Cypress, Selenium, Puppeteer
  • Example: Testing a user’s ability to log in, navigate through the app, and complete a purchase.

4. What is @coding-library/react?

This is a library that provides testing utilities specifically for React applications. It helps in writing and running tests for React components and ensuring their proper functionality.

5. What is Jest?

A JavaScript testing framework developed by Facebook that provides a comprehensive set of features for testing. It supports unit, integration, and end-to-end testing with built-in test runners, assertions, and mocking capabilities.

Features:

  • Snapshot Testing: Capture component output and compare it over time.
  • Mocking: Create mock functions and modules to isolate components.

What is jsdom: A JavaScript implementation of the DOM used by Jest to simulate a browser environment for running tests. It allows you to test React components and other DOM interactions without needing a real browser.

6. How to Write a Test

Create test cases to verify specific functionalities. Tests typically include:

  • Setup: Prepare the environment and initial conditions.
  • Execution: Perform actions or trigger events.
  • Assertion: Check if the outcomes match expected results.
  • Cleanup: Restore the environment if needed.

7. React Unit Tests

  • Test if a Page is Loaded or Not:

    import { render } from "@testing-library/react";
    import App from "./App";
    
    test("renders the page", () => {
      render(<App />);
      // Assert something that confirms the page has loaded
    });
    
  • Test if an Element is Loaded or Not:

    import { render, screen } from "@testing-library/react";
    import MyComponent from "./MyComponent";
    
    test("renders an element", () => {
      render(<MyComponent />);
      const element = screen.getByText("buy now");
      expect(element).toBeInTheDocument();
    });
    
  • Test onClick Event of a Button:

    import { render, screen, fireEvent } from "@testing-library/react";
    import MyButton from "./MyButton";
    
    test("button click triggers event", () => {
      const handleClick = jest.fn();
      render(<MyButton onClick={handleClick} />);
      fireEvent.click(screen.getByText("click me"));
      expect(handleClick).toHaveBeenCalled();
    });
    
  • Test a Component with Props/Data:

    import { render, screen } from "@testing-library/react";
    import MyComponent from "./MyComponent";
    
    test("renders component with props", () => {
      render(<MyComponent data="test data" />);
      expect(screen.getByText("test data")).toBeInTheDocument();
    });
    
  • Integration Testing: Fetching Data from API:

    import { render, screen, act } from "@testing-library/react";
    import MyComponent from "./MyComponent";
    import axios from "axios";
    
    jest.mock("axios");
    
    test("fetches and displays data", async () => {
      axios.get.mockResolvedValue({ data: { key: "value" } });
      await act(async () => {
        render(<MyComponent />);
      });
      expect(screen.getByText("value")).toBeInTheDocument();
    });
    

fireEvent: A utility from @testing-library/react used to simulate user interactions like clicks, typing, etc.

9. jest test --watch

A command that runs Jest in watch mode. It automatically reruns tests when changes are detected in the source files, providing a more efficient testing workflow.

10. beforeAll(), afterAll(), beforeEach(), and afterEach()

  • beforeAll(): Runs once before all the tests in a file.
  • afterAll(): Runs once after all the tests in a file.
  • beforeEach(): Runs before each test in a file.
  • afterEach(): Runs after each test in a file.
beforeAll(() => {
  // Setup code before any tests run
});

afterAll(() => {
  // Cleanup code after all tests have run
});

beforeEach(() => {
  // Setup code before each test
});

afterEach(() => {
  // Cleanup code after each test
});

11. What is Coverage Folder and Coverage Report

  • Coverage Folder Contains the results of code coverage analysis, typically including files like lcov-report that provide details on the percentage of code executed during tests.
  • Coverage Report is A report generated by testing tools (like Jest) that shows which lines, branches, functions, and statements in your codebase were covered by tests. It helps identify untested parts of the code.