Challenge: Cypress Component Testing
Learn and practice component testing with Cypress by mocking dates.
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_DAY
constant, which is the number of milliseconds in a day.Lines 5–8: We create a new
Intl.RelativeTimeFormat
object with theen_US
locale,style
set tolong
, andnumeric
set toauto
. 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
, oryears
).Line 11: We round down the return of the
days
divided by7
to get the number of weeks. ...