Search⌘ K
AI Features

Challenge: Cypress Component Testing

Explore Cypress component testing by learning to test a TimeCalculator React component that shows relative time differences. Understand how to mock global dates for reliable tests and write assertions for outputs like today, tomorrow, and yesterday to ensure your component behaves correctly in various scenarios.

We'll cover the following...

Let’s practice component testing by testing a relative time difference calculator.

Time calculator component

This component renders a paragraph showing the difference between two dates in either days, weeks, months, or years. We can see the component in action on the individual meetup pages found in /pages/[slug].tsx file.

import { TimeCalculator } from "../../src/TimeCalculator";

describe("timeCalculator", () => {
  it("shows correct date today", () => {
    const mockDateNow = new Date(2023, 0, 1, 12, 0);
    cy.clock(mockDateNow);
    cy.mount(<TimeCalculator date={new Date(2023, 0, 1, 12, 0)} />);

    cy.contains("today");
  });

  it("shows correct date tomorrow", () => {
    const mockDateNow = new Date(2023, 0, 1, 12, 0);
    cy.clock(mockDateNow);
    cy.mount(<TimeCalculator date={new Date(2023, 0, 2, 12, 0)} />);

    cy.contains("tomorrow");
  });

  it("shows correct date yesterday", () => {
    const mockDateNow = new Date(2023, 0, 1, 12, 0);
    cy.clock(mockDateNow);
    cy.mount(<TimeCalculator date={new Date(2022, 11, 31, 12, 0)} />);

    cy.contains("yesterday");
  });
});

export {};
React time formatter component

Let’s navigate to the /src/TimeCalculator.tsx file.

  • Line 3: We have a MS_IN_DAY constant, which is the number of milliseconds in a day.

  • Lines 5–8: We create a new Intl.RelativeTimeFormat object with the en_US locale, style set to long, and numeric set to auto. This object allows us to easily and reliably format values and units into the English natural language.

  • Lines 10–24: We define our timeFormatter function, which takes a number representing the number of days and returns a formatted string representing the duration in relative time units (days, weeks, months, or years).

    • Line 11: We round down the return of the days divided by 7 to get the number of weeks. ...