Intro to Web Testing with Cypress
As a web developer, you know that building a web application is a complex process that requires many moving parts to work together seamlessly. The way to ensure that your application works as expected and that it is free of bugs and errors is testing.
In this tutorial, I will introduce you to Cypress, a tool that makes it easy to test your web applications, no matter the source technology.
What is Cypress?
Cypress is an open-source testing framework designed to make writing and running tests for web applications accessible. It is built on top of modern web technologies such as Node.js and Electron, and it provides a robust API for interacting with web pages and applications.
🎒 Prerequisites.
If you are new in the testing field, I recommend reading my introduction to testing techniques.
🌱 Getting Started with Cypress
To get started with Cypress, you’ll need to install it on your machine. Once done, you need to open it, and on the first run, it will auto-configure so you can start writing tests for your web applications.
Cypress tests are written using TypeScript (or JavaScript) and designed to simulate user actions on a web page or application. You can add it to the target project you want to test. Or generate a completely different testing project, as I will do in this tutorial. The minimum required for a project to host your tests is like the following.
# A bare-bone TS project
npm init --yes
npm i -D typescript
npx tsc --init
# Install cypress (could be -D when adding to the target project)
npm i cypress
# package.json "scripts" "start": "cypress open"
npm start
Once done, you might write a test that clicks a button, fills out a form, or navigates to a different page. Cypress allows you to simulate these actions in your tests quickly. Let’s see how.
🌲 Writing Tests with Cypress
You write your tests in name.cy.ts
files in the cypress/e2e`
folder. Inside, you will group your testing code into describe(description,()=>{})
blocks with assertions inside functions like it(description, ()=>{})
.
describe("The page or functionality being tested", () => {
it("should work as expected", () => {
// Arrange: prepare for the test
// Act: user simulation commands
// Assert: express your expectations
});
});
Cypress is based on the powerful Chai syntax. You will write every simulated user action with a command; you might use the cy.visit()
to navigate to a specific page or the cy.get()
to select an element on the page and make assertions with the result using .should()
.
describe("The target page", () => {
it("should have a h1 title", () => {
cy.visit("https://www.your-app.com/");
cy.get("h1").should("exist");
});
});
Once you have selected an element, you can chain more commands to interact with it. For example, you might use the cy.click()
command to click on a button or the cy.type()
command to enter text into a form field.
describe("The login page", () => {
it("should allow to fill the form", () => {
cy.visit("https://www.your-app.com/auth/login");
cy.get("#username").clear().type("Alberto Basalo");
cy.get('[type="email"]').clear().type("alberto@mail.server");
cy.get('[type="password"]').first().type("123a");
cy.get('[name="repeatPassword"]').type("123a");
cy.get("form button[type=submit]").click();
});
});
Select items with Cypress as you would with JQuery
As you saw in the previous code, there are different ways to select elements with Cypress commands. You can use your JQuery and DOM selection knowledge.
Be aware of changes in code that may break your tests. If you can control the source code, explicitly declaring attributes for testing purposes is preferable. That way, the test will survive implementation changes in names, CSS classes…
it("should show an error for user name while invalid", () => {
cy.get("#username").clear().type("a");
cy.get("[data-test='username.error']").should("be.visible");
});
Assertion clauses
Selecting and acting like users are the first steps in any Cypress test. But the real magic comes from the assertions, where you set your expectations.
One more time, you are covered with the simplicity and elegant way of expressing assertions clauses with Cypress. Here you have a set of samples to get an idea.
it("should contain '© Alberto Basalo' in the footer", () => {
cy.get("footer").contains("© Alberto Basalo");
});
it("should have an h1 with 'My Big App' text", () => {
cy.get("h1").should("have.text", "Big App");
});
it("should navigate to the sign-up page", () => {
cy.get("header>nav a").contains("Sign up").click();
cy.url().should("include", "auth/sign-up");
});
it("should mark the email as invalid if it is not an email", () => {
cy.get('[type="email"]').clear().type("not-an-email");
cy.get('[type="email"]').should("have.class", "ng-invalid");
});
🍏 Running Tests with Cypress
Once you have written your tests, you can run them using the Cypress Test Runner. The cypres open
command provides a visual interface for running and debugging your tests. You can use the Test Runner to watch your tests run in real-time, and you can use it to debug any issues that you encounter. It is the ideal way to test along while coding.
For running your tests as a part of a CI/CD process, you can launch your tests in an unattended way using the cypress run
command. In this case, Cypress will produce a text-based report that you can save to a file.
In any case, you can take snapshots or even videos of any process or specific steps. This way, anyone can be sure of what happened during the execution of the test suite.
Need help testing your apps❓
I offer a coaching service with Cypress.🌲
🌅 Summary.
Testing is an essential part of building web applications. Cypress is a robust testing framework that makes writing and running tests for your web applications really easy.
With its powerful API and easy-to-use Test Runner, Cypress is an excellent choice for web developers who want to ensure the quality and reliability of their applications.
You can get more examples in this project that I use during my courses.
For advance tips, go ahead and read my next article:
So why not give it a try? Install Cypress today and start writing tests for your web applications!