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 {};
Let’s navigate to the /src/TimeCalculator.tsx file.
Line 3: We have a
MS_IN_DAYconstant, which is the number of milliseconds in a day.Lines 5–8: We create a new
Intl.RelativeTimeFormatobject with theen_USlocale,styleset tolong, andnumericset toauto. This object allows us to easily and reliably format values and units into the English natural language.Lines 10–24: We define our
timeFormatterfunction, which takes a number representing the number of days and returns a formatted string representing the duration in relative time units (days,weeks,months, oryears).Line 11: We round down the return of the
daysdivided by7to get the number of weeks. ...