All articles

Start testing your react app

lang
EN
link
date
Aug 31, 2021
slug
react-test
status
Published
tags
React
Testing
summary
When I first started learning to test my apps back in the day, I would get very frustrated with the different types, styles and technologies used for testing, along with the disbanded array of blog posts, tutorials and articles. I found this to be true as well for React testing.
type
Post

Why testing

  • Goal: check whether an application behaves as expected
  • Safeguard against unwanted behaviour when changes are made
  • Automated, and thus efficient on the long-term
Example test priority:
  1. Hign value features
  1. Edge cases in high value features
  1. Things that are easy to break
  1. Basic React component testing
      • User interactions
      • Conditional rendering
      • Utils / Hooks

Setup demo project

install the dependencies & run the project
Shell
yarn install && yarn dev

Recognize what to test

Hign value features:
  1. Account balance & transactions
  1. make a payment
Edge cases in hign value features:
  1. make a payment without entering the amount etc...
Easy to break:
Component testing:
  1. form component

Ways to test

Unit testing

Unit testing is a type of testing in which individual units or functions of software testing. Its primary purpose is to test each unit or function. A unit is the smallest testable part of an application.
  • Simple test example
  1. Create a file with the extension test.js
notion image
  1. Use the react test library to test
JavaScript
import { render, screen } from "@testing-library/react";
import TransactionCreateStepTwo from "./TransactionCreateStepTwo";

test("on initial render, the pay button is disabled", () => {
  render(<TransactionCreateStepTwo sender={{ id: "123" }} receiver={{ id: "456" }} />);

  screen.debug();
});
  1. Unit test
notion image
  • Implementing the test logic
JavaScript
test("on initial render, the pay button is disabled", async () => {
  render(<TransactionCreateStepTwo sender={{ id: "123" }} receiver={{ id: "456" }} />);

  // expect wheather the button to be disabled
  expect(await screen.findByRole("button", { name: /pay/i })).toBeDisabled();
});

test("if an amount and note is entered, the pay button becomes enabled", async () => {
  render(<TransactionCreateStepTwo sender={{ id: "123" }} receiver={{ id: "456" }} />);

  // expect wheather the button to be disabled
  expect(await screen.findByRole("button", { name: /pay/i })).toBeDisabled();

  // typing the test value
  userEvent.type(screen.getByPlaceholderText(/amount/i), "50");
  userEvent.type(screen.getByPlaceholderText(/add a note/i), "50");

  // expect wheather the button to be enabled after typing the value
  expect(await screen.findByRole("button", { name: /pay/i })).toBeEnabled();
});

Intergration testing

Integration testing is the phase in software testing in which individual software modules are combined and tested as a group.

End-to-End testing 🔥

  1. install & start Cypress
Shell
yarn add -D cypress @testing-library/cypress
yarn run cypress open
  1. write the test logic in integration folder
notion image
  1. the test file will be shown up in Cypress client
notion image
  1. click run and you can see how the testing is going
notion image

Wrap up

  • Always remember why you test
  • Set priorities
    • E2E
      1. High value features.
      Integration/Unit
      1. Edge cases in high value features
      1. Things that are easy to break
      1. Basic React component testing
    • User interactions
    • Conditional rendering
    • Utils / Hooks
    •  
payment_spec.js
JavaScript
const { v4: uuidv4 } = require("uuid");

describe("payment", () => {
  it("user can make payment", () => {
    // login
    cy.visit("/");
    cy.findByRole("textbox", { name: /username/i }).type("johndoe");
    cy.findByLabelText(/password/i).type("s3cret");
    cy.findByRole("checkbox", { name: /remember me/i }).check();
    cy.findByRole("button", { name: /sign in/i }).click();

    // check account balance
    let oldBalance = cy
      .get("[data-test=sidenav-user-balance]")
      .then(($balance) => (oldBalance = $balance.text()));

    // click on click button
    cy.findByRole("button", { name: /new/i }).click();

    // search for user
    cy.findByRole("textbox").type("devon becker");
    cy.findByText(/devon becker/i).click();

    // add amount and note and click pay
    const paymentAmount = "5.00";
    cy.findByPlaceholderText(/amount/i).type(paymentAmount);
    const note = uuidv4();
    cy.findByPlaceholderText(/add a note/i).type(note);
    cy.findByRole("button", { name: /pay/i }).click();

    // return to transactions
    cy.findByRole("button", { name: /return to transactions/i }).click();

    // go to presonal payments page
    cy.findByRole("tab", { name: /mine/i }).click();

    // click on payment
    cy.findByText(note).click({ force: true });

    // verify if payment was made
    cy.findByText(`-$${paymentAmount}`).should("be.visible");
    cy.findByText(note).should("be.visible");

    // verify if payment amount was deducted
    cy.get("[data-test=sidenav-user-balance]").then(($balance) => {
      const convertedOldBalance = parseFloat(oldBalance.replace(/\$|,/g, ""));
      const convertedNewBalance = parseFloat($balance.text().replace(/\$|,/g, ""));
      expect(convertedOldBalance - convertedNewBalance).to.equal(parseFloat(paymentAmount));
    });
  });
});