Published: 08.12.2020 | Edited: 22.12.2020 | Tags: javascript,cypress

How to assert sorted dates in Cypress

Here's how I use Cypress to assert that the user interface I am building displays datetime information sorted chronologically. Consider the list of dates served at the port 3000 that looks like this:

<ul id="sorted">

I live in Europe and the format we write dates in is

  • Start by installing Cypress dev dependencies
npm i -D cypress start-server-and-test date-fns
  • Create cypress.json and make sure the port matches your app's port
  "baseUrl": "http://localhost:3000"
  • Edit package.json and suit it to your needs by also matching the app's port
"scripts": {
    "dev": "node .",
    "cy:run": "cypress run",
    "test": "start-test dev 3000 cy:run"
  • Initialize Cypress
npx cypress run && mkdir -p cypress/integration
  • Create the test at cypress/integration/spec.js
/// <reference types="cypress" />
import { parse } from "date-fns"

describe("Date list should", () => {
  it("have dates sorted chronologically", () => {

    const parseDate = date => parse(date, "dd.MM.yyyy", new Date())
    let prevDate = parseDate("01.01.1970")

    cy.get("ul#sorted li").each($pre => {
      const currentDate = parseDate($pre.text())

      prevDate = currentDate
  • Note that Cypress.moment being deprecated1 as of Cypress v6.1.02 is the reason date-fns was used

  • Run the test

npm run test


The sources are available in the repository

Further reading