Frontend Testing with Cypress: Ensuring a Flawless User Experience
Section titled “Frontend Testing with Cypress: Ensuring a Flawless User Experience”We use Cypress for frontend testing. It runs real browser tests, gives you live feedback, and works with React, Vue, Angular, and most other frontend frameworks.
Setting Up Cypress
Section titled “Setting Up Cypress”- Install Cypress as a dev dependency:
npm install cypress --save-dev- Add a test script to
package.json:
{ "scripts": { "test": "npx cypress open" }}- Run Cypress for the first time:
npm run testCypress will open its test runner and create example files so you have something to start from.
Writing Your First Test
Section titled “Writing Your First Test”-
Create a new file in the
cypress/e2edirectory. Name itmy_first_test.cy.js. -
Add this code:
/// <reference types="cypress" />
describe("example to-do app", () => { beforeEach(() => { cy.visit("https://example.cypress.io/todo"); });
it("displays two todo items by default", () => { cy.get(".todo-list li").should("have.length", 2);
cy.get(".todo-list li").first().should("have.text", "Pay electric bill"); cy.get(".todo-list li").last().should("have.text", "Walk the dog"); });});- Start your development server, then run Cypress:
npm run test- Select your test file from the Cypress Test Runner.
Cypress will open a browser and run through the test steps in real time.