Common Cypress Test Cases with Examples

Photo by Emile Perron
Photo by Emile Perron on Unsplash

Introduction

So, you’ve embarked on your coding journey, and you’ve heard about the magical world of Cypress for E2E testing. But where do you start? Fear not, fellow developer, for we’re here to walk you through common Cypress test examples, cases, and ideas in a way that’s as exciting as discovering a hidden treasure map in your codebase.

Are you new to Cypress? Learn how to set up Cypress testing for your project.

Unpacking Cypress Magic

Before we dive into the wonderful world of Cypress tests, let’s address the elephant in the room: why do we even need E2E tests? Imagine your web application is a labyrinth, and your users are intrepid adventurers navigating it. E2E tests are your trusty guides, making sure your users don’t fall into traps or get lost in the maze.

End-to-end tests are like Gandalfs that guide your users safely through your web app!

Login Test Example

it("Login Test", () => {
  // Visits a specific URL
  cy.visit("/login");

  // Find input of certain type and type in text
  cy.get('[type="email"]').type('john.doe@example.com');

  // Find button with certain text and click it
  cy.get("button").contains("Login").click();

  // Check whether the new URL contains certain text (e.g. after successful login)
  cy.url().should("include", "/dashboard");

  // Find button with certain `data-test` attribute and click it
  cy.get('[data-test="test-button"]').click();
});
  • cy.click(): Simulates a click on the selected element, triggering any associated events
  • cy.contains(text): Selects an element that contains the specified text, making it useful for locating elements with specific content
  • cy.get(selector): Selects and targets a DOM element based on its CSS selector, allowing you to interact with it
  • cy.should('condition'): Asserts that the currently selected element or elements meet the specified condition, such as ‘be.visible’, ‘contain’, or ‘have.attr’
  • cy.type(text): Types the specified text into the currently selected input field or textarea
  • cy.url(): Retrieves the current URL of the page, enabling you to check if the navigation worked as expected
  • cy.visit(url): Navigates to the specified URL, allowing you to start your test on a particular page

Element Count Example

it("Counting Div", () => {
  // Expects 10 divs with class `app`
  cy.get('div.app').should(($div) => {
    expect($div).to.have.length(10);
  });
});
  • cy.expect(): Asserts that a value meets a certain condition

Image URL Test Example

it("Testing Image URL is Valid", () => {
  const url = '/img/image.jpg';
  cy.request({
    encoding: 'base64',
    url
  }).should(($response) => {
    expect($response.status).to.eq(200);

    const mime = $response.headers['content-type'];
    expect(mime).to.eq('image/webp');

    const base64Content = $response.body;
    const imageDataUrl = `data:${mime};base64,${base64Content}`;
    const img = new Image();
    img.src = imageDataUrl;
    img.onload = () => {
      // Expects width of image to be 1024px
      expect(img.naturalWidth).to.eq(1024);
    };
  });
});

it("Testing Image URL is invalid", () => {
  const url = '/img/not-an-image.jpg';
  cy.request({
    failOnStatusCode: false,
    url
  }).should(($response) => {
    expect($response.status).to.eq(404);
  });
});
  • cy.request(url): Makes an HTTP request

More Cypress Test Commands

Here are some more Cypress test commands that you may find useful:

  • cy.blur(): Blurs a focused DOM element
  • cy.check(): Checks a checkbox
  • cy.clear(): Clears the value of a DOM element
  • cy.debug(): Opens a debugger to inspect the current state of the application
  • cy.exec(command): Executes a shell command on your local system, often used for setting up or tearing down test data
  • cy.fixture(filename): Load a fixture file
  • cy.focus(): Focuses a DOM element
  • cy.go(): Navigates to the previous or next page in the browser history
  • cy.intercept(route, handler): Intercepts and stubs network requests, which is useful for testing API calls and responses
  • cy.reload(): Reloads the current page
  • cy.scrollTo(): Scrolls to a specific element on the page
  • cy.select(): Selects an option from a dropdown menu
  • cy.uncheck(): Unchecks a checkbox
  • cy.wait(time): Waits for a specific condition to be met
  • cy.wrap(subject): Wraps an object so that it can be chained with Cypress commands

Helpful Tips:

Here are some helpful tips for writing Cypress tests:

  • Use descriptive test names: This will make your tests easier to understand and maintain.
  • Organize your tests into logical groups: This will help you to keep your tests organized and easy to find.
  • Use fixtures to store common data: This will help you to avoid repeating yourself in your tests.
  • Use assertions to verify that your tests are passing: Assertions allow you to test the expected behavior of your application.
  • Use screenshots and videos to capture failures: This will help you to debug your tests and identify the root cause of failures.

Conclusion

Cypress is a powerful and easy-to-use testing automation framework. By following the tips in this article, you can write Cypress tests that will help you to ensure the quality of your applications.

Share: