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">
<li>14.12.1999</li>
<li>12.03.1975</li>
<li>28.02.2001</li>
<li>20.08.2010</li>
<li>05.07.2018</li>
</ul>
I live in Europe and the format we write dates in is dd.mm.yyyy
- 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", () => {
cy.visit("/")
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())
expect(prevDate).to.be.lte(currentDate)
prevDate = currentDate
})
})
})
-
Note that
Cypress.moment
being deprecated as of Cypress v6.1.0 is the reasondate-fns
was used -
Run the test
npm run test
Done!
The sources are available in the repository