Introduction to Cypress

Marek Grušpier / 15.11.2023

Testing is a crucial part of web development. It ensures that your application is functioning as expected and helps catch bugs before they make it to production. However, testing can often be a tedious and time-consuming process. This is where Cypress comes in. Cypress is a JavaScript-based end-to-end testing framework that aims to make testing your web applications easier, faster, and more reliable.

Why use Cypress?

Cypress provides a complete testing environment that includes a browser, test runner, and assertion library. This means you can write and run tests in a real browser, giving you a more accurate representation of how your application will behave in the real world. Cypress also provides a powerful and intuitive test runner that allows you to see the results of your tests in real-time as you write and modify them.

Cypress is also designed to provide fast feedback during test development. It has a range of powerful tools for interacting with your web application, including robust DOM manipulation and debugging tools. This allows you to quickly identify and fix issues, making the testing process much more efficient.

In addition to its core functionality, Cypress also provides a range of plugins and integrations that can help extend its capabilities even further. For example, there are plugins available for testing APIs, integrating with CI/CD systems, and more.

How does Cypress work?

Cypress works by running your tests in a real browser. This allows you to interact with your web application just like a real user would, making it easier to identify issues that might not be caught by other testing frameworks.

Cypress provides a range of APIs for interacting with your application, including cy.get() for selecting elements, cy.click() for simulating clicks, and cy.type() for simulating typing. These APIs are designed to be intuitive and easy to use, allowing you to write tests quickly and efficiently.

One of the key features of Cypress is its ability to provide fast feedback during test development. As you write and modify your tests, Cypress will automatically rerun them in real-time, giving you immediate feedback on whether your changes have introduced any issues.

Getting started with Cypress

Before you start using Cypress, there are a few prerequisites that you should have in place:

  1. Node.js: Cypress is built on top of Node.js and requires it to be installed on your machine. You can download the latest version of Node.js from the official website:
    https://nodejs.org/en/download/.
  2. After Node.js is installed, open a terminal or command prompt and type the following command to check if Node.js and npm are installed and to display their version numbers:

node -v

npm -v

This should display the version numbers of Node.js and npm, indicating that they are installed.

After node.js is installed successfully we can install Cypress using npm:

npm install cypress --save-dev

Once installed, you can open the Cypress Test Runner using the following command:

npx cypress open

This will open the Cypress Test Runner, where you can create and run tests for your web application.

Commonly used Cypress features

Hooks

Cypress hooks are functions that allow us to perform actions at specific points in the testing process. They are designed to help automate repetitive tasks and make it easier to manage complex test scenarios. Cypress provides several hooks that can be used to execute code before or after a test run, a test suite, or individual test cases. In our project, we used: 

beforeEach(): This hook is executed before each individual test case in a suite. It is typically used to reset the environment or set up test data for each test.

afterEach(): This hook is executed after each individual test case in a suite. It is typically used to clean up the environment or reset any changes made during the test.

Other hooks:
before(): This hook is executed once before any of the tests in a suite are run. It is typically used to set up test data or configure the environment for the tests.

after(): This hook is executed once after all of the tests in a suite are run. It is typically used to clean up resources or perform final actions after the tests have completed.

Commands

Custom Cypress commands are user-defined functions that can be reused across multiple test files. They are helpful in reducing code duplication and increasing code maintainability. 

  1. Create a new JavaScript file in your Cypress project and define your custom command as a function
Cypress.Commands.add('login', (email, password) => {
    cy.contains('Sign in').click()
    cy.get('[type=email]').as('email').type(email)
    cy.get('[type=password]').as('password').type(password)
    cy.get('button[type=submit]').as('SignIn').click()
    cy.log("Loging in")
})

Cypress.Commands.add('logout', () => {
    cy.get(':nth-child(3) > .nav-link').click()
    cy.get('.btn-outline-danger').click()
    cy.log("Loging out")
})

2. In your test file, you can now call the custom command by its name:

cy.login('email', 'password')
cy.logout()

Intercept

Cypress Intercept method is a powerful feature of the Cypress testing framework that allows you to intercept and modify HTTP requests and responses in your application during testing. With this method, you can simulate various network scenarios and test your application’s behavior in response to them.

The Intercept method works by intercepting all outgoing network requests and replacing them with mock responses or modifying them in real-time. This enables you to test your application’s behavior under various network conditions, such as slow network speeds, failed requests, and unexpected responses.

To use the Cypress Intercept method, you can call the cy.intercept() command in your test code and pass in a route object with details about the request you want to intercept. You can then define a response object or a callback function that will modify the response before it reaches your application.

For example, you can intercept a request to a specific URL and return a custom response with the following code:

cy.intercept('/api/data', { fixture: 'example.json' })

This intercepts any requests made to the /api/data endpoint and returns the response defined in the example.json fixture file.

Overall, the Cypress Intercept method is a powerful tool for testing your application’s network behavior and ensuring that it performs correctly under a variety of conditions.

Wait

The wait() method in Cypress allows you to pause the test execution and wait for a specific condition to be true before continuing. This is useful when you need to wait for an element to appear on the page, for an API call to complete, or for any other asynchronous operation to finish.

The wait() method takes a number of different arguments depending on the type of condition you are waiting for. For example, you can wait for an element to exist on the page using a CSS selector, or you can wait for a specific URL to be loaded.

Here is an example of using the wait() method to wait for an element with the CSS selector #my-element to appear on the page:

cy.get('#my-element').should('exist').wait(1000);

In this example, Cypress will first try to find the element with the CSS selector #my-element. Once it finds the element, it will check that it exists using the should() command. If the element exists, Cypress will then pause the test execution for 1000 milliseconds (1 second) using the wait() method.

Alias

In Cypress, an alias is a way to assign a name to a particular element or group of elements in your application. This name can then be used throughout your test code instead of having to repeatedly select the element(s) using a selector.

To create an alias, you can use the as keyword in combination with the cy.get() command. Here’s an example:

cy.get('.my-class').as('myElement')

In this example, we’re using the cy.get() command to select an element with the class name “my-class”, and then assigning it the alias “myElement”. Now we can refer to this element using its alias instead of the selector:

cy.get('@myElement').click()

This will click on the element that was previously selected and aliased. Aliases can also be used to group together multiple elements under a single name. Here’s an example:

cy.get('.my-class').as('myElements')

In this case, we’re selecting all elements with the class name “my-class” and assigning them the alias “myElements”. Now we can refer to all these elements using their alias:

cy.get('@myElements').should('have.length', 3)

This will check that there are exactly three elements with the class name “my-class” that were previously selected and aliased. Using aliases can make your test code more readable and easier to maintain, especially when dealing with complex web applications with lots of elements and selectors.

Conclusion

Cypress is a powerful and user-friendly testing framework that can help you build better, more reliable web applications. Its intuitive APIs, powerful test runner, and real browser testing environment make it an ideal choice for front-end developers and testers who want to streamline their testing process and improve the quality of their applications. If you aren’t already using Cypress in your testing process, the time to give it a try is now!

Marek Grušpier

I’ve been working in the testing industry for 4 years. I’m excited to explore the latest advancements in technology, with a keen interest in staying up to date with the latest trends and innovations. Currently working on a front-end test automation project. Apart from work, I’m an avid gamer, a gym rat, and a history nerd.

Share:

Stay tuned

Be among the first who get to know the latest developments, innovations, & trends.