13 Examples Of Cypress


In the last article, we saw what Cypress is, its architecture, the installation process, and the pre-requisites required for the installation. However, before we begin writing our tests, we need to install Cypress. Click here to get the detailed steps to install Cypress.

Cypress Example

This article will discuss the Cypress example, JSON examples, variables and aliases, and how to write test cases. So let’s get started.

Cypress Example
Cypress Example

Table of Contents

Cypress JSON Example

Initially, when we open our Cypress Test Runner, a cypress.json configuration file is created. We tend to store the snippet that provides a way to implement and keep some properties that help in the program or automation code to execute. Similarly, Cypress also has a JSON file to store any values that we supply as configuration properties.

Let us look into some examples that we can configure in our Cypress JSON file.

Cypress already has some default configuration values assigned. There are several options that we can customize based on our requirements. For instance, we can provide the baseURL property in our cypress.json file. So, every time we run the script, the baseURL is set and triggers.

OptionDefault valuesDescription
baseUrlnullThis option can be used as a URL prefix for the cy.request() or cy.visit() commands.
watchForFileChangestrueThis option is set as true by default. It watches the files for changes and restarts them when any modifications are made.

Below is the snapshot that we have modified baseURL and watchForFileChanges properties in our Cypress.json file.

Note: We will be discussing all the options in Cypress Configuration as a separate topic later.

Cypress Example
cypress.json file

Open Cypress

Earlier, we saw about how to create a Cypress project. Here, we will see how to open and execute the Cypress Test runner. So let’s dive in!

If you had installed Cypress via npm, then it has been installed in the ./node_modules directory. Hence, we can open our Cypress test runner by passing an npm command from the root of our project directory.

We can open Cypress in one of the following ways

1. by giving the full path command

./node_modules/.bin/cypress open

2. by using the shortcut for npm bin

$(npm bin)/cypress open

3. by using npx

Here npx is supported only with npm > v5.2, or we can install it separately.

npx cypress open

4. by using yarn

yarn run cypress open

Now we will see how to open Cypress by passing the full path command in our terminal.

1. You have to pass the command that is mentioned above in point 1, and you can see the following in the terminal

Opening Cypress in Terminal

2. After a moment, we can see the Cypress Test runner launching and will be able to view the Test runner as shown below. After the test runner has launched, you could see some sample test cases. Cypress has created a test folder in our project root that helps us with the basic setup and writing of test cases.

Example files in Test Runner

Now let us go back to VS Code. First, you can view some folder structures that got populated. Now let us break down each of the folder structures and look at them in detail.

Folder Structure in Cypress

As we see, Cypress has created a folder structure in our code editor. We will discuss them in detail.

Folders in Cypress Example
  1. Fixtures – The fixture folder contains the data that is static and is reusable throughout the project. One best practice is not hardcore data(like credentials, test messages) in our tests. Instead, we access them in via a JSON, CSV, or HTML file. We should create our data files under the fixture folder. We access this file in our test using cy.fixture command.
  2. Integration – Under this folder, we write the actual test cases that we usually call a spec file. Inside the integration folder, we can create multiple folders and many test files under each folder based on our project requirements. You can also see some default spec files produced with some examples.
  3. Plugins – Plugins folder contains files that enable you to tap, access, and modify Cypress’s internal working behavior. With plugins, you can write the custom code that can help you execute the test commands that have direct access to every part(before or after execution) of your code structure. By default, Cypress creates the plugins in this path cypress/plugin/index.js
  4. Support -Under the support folder, we have the files that help us provide standard or reusable methods. Before every spec run, Cypress executes the Support folder. So it is not necessary to import the support file in every other spec file. This folder is the right place to add reusable methods or global functions essential to be used over all the other spec files.
  5. Node modules – This folder contains all the npm packages that we installed. Node modules are significant to run any node project. All the functions that are in our Cypress project are written inside our node modules folder. We will not be modifying any files inside node modules.
  6. Cypress.json – We can add multiple configurations in our Cypress.json file. For instance, we can add environment variables, baseURL, timeouts, or any other options to override the default options in the Cypress configuration file.

Variables and Aliases

We shall discuss the variables and aliases in Cypress in detail.

As we understand and learn Cypress, it might be difficult for us to understand the Asynchronous API nature in Cypress. But as we see many examples in the future, it would become a piece of cake. Many modern browsers use asynchronous APIs, and even core Node modules are written with asynchronous code. Moreover, Asynchronous code is present everywhere in Javascript code. Therefore, we will be looking into the return values in Cypress.

Return Values In Cypress

All the Cypress commands are enqueued and run asynchronously. Therefore, we cannot assign or interact with any return values of any Cypress commands. We will see a little example of the same.

const button = cy.get("login-btn");  //this command is to get the element with the button attribute

button.click()

Closures

We cannot access the attributes of the button via the command mentioned above. Instead, we can yield Cypress commands by using .then(). We call these closures.

.then()

.then() helps you to access the thread that is yielded from the previous command. If you have understood native promises, it is the same way .then() works with Cypress. We can also nest different commands inside .then(). Each nested command can access the previous command in the loop. We will see that with an example.

cy.get('login').then(($btn) => {

  // store the button's text
  const buttonText = $btn.text()

  // we are comparing the two buttons' text
  // and ensuring they are different
  cy.get('login').should(($btn2) => {
    expect($btn2.text()).not.to.eq(buttonText)
  })
})

We have used Closures in the above example, enabling us to keep the reference of the previous command in the loop.

Variables

Usually, we tend to assign a value to a variable. But in Cypress, we barely use const, var, and let. When we are using closures, we can access the yielded objects without assigning them to a variable.

But there are some cases where we can declare a variable is when the object’s state changes (mutable objects). For example, if we require comparing an object to its previous value, we will be declaring them to a variable to compare it with the next value. Let us look into an example for this.

<button>increment</button>

You clicked button <span id="num">0</span> times

Here, the span with the count 0 keeps increasing each time we click the button. So the button object tends to change its state every time.

Now let’s look into how we can assign this to a variable in our Cypress code.

cy.get('#num').then(($span) => {
  // we are capturing the number by assigning it to a variable
  const num1 = parseFloat($span.text())

  cy.get('button')
    .click()  //we have clicked the button once
    .then(() => {
      // we are capturing the number again by assigning it to another variable
      const num2 = parseFloat($span.text())

      // we are ensuring that num1+1 is equal to num2
      expect(num2).to.eq(num1 + 1)
    })
})

Since span is changing its state every time we click the button, we can assign it to a variable to compare its present and previous state. Only in the case of mutable objects will we require variables, and using const is a good approach.

Aliases

Previously, we saw what variables and its limitation in Cypress is. To overcome this limitation, Aliases comes into the picture. Alias is one of the powerful constructs in Cypress. We will look into this in detail with examples.

Generally, Aliases can help you to work as a variable. However, there are some use cases where an alias can help us instead of a variable.

1. Reuse DOM Elements

We can alias DOM elements and later access them for reuse. Aliases also overcome the limitations of .then() command.

2. Sharing context

In simple meaning, sharing context is sharing the object between the hooks and the tests. The primary use case for sharing context is dealing with cy.fixture – which is to load a fixed set of data in a file.

How to access aliases?

Here, we will see how to access aliases. We will be using the .as() command to assign the element for later use. The required parameter is the alias name. The alias’ name is used as a reference within a cy.get() or cy.wait() using the @ prefix.

We will look into an example of how to access aliases.

cy.get('#user_login').as('username')
cy.get('@username').type('abc@gmail.com')

In the first line, we are getting the id of the user_login from DOM. We are then using .as() and declaring with a name username. In the second line, we are accessing our alias with @ symbol and performing the type action.

Cypress Test Example

We will begin writing our first test case with Cypress. It is very simple and easy. But before that, we will look into the constructs of the Cypress test.

Basic Cypress Constructs

Cypress has adopted the Mocha syntax for its test cases and uses all the options Mocha provides. Below are the basic Cypress constructs that are used in common for our test cases.

  • Describe() – combines all the test cases into a single larger test and groups them together. It takes two parameters – the description of the test and a callback function.
  • it() – we write individual test cases in our it() block. This block also takes two parameters- what a test does, and the second parameter is the callback function.
  • after() – this executes after all the tests in the spec file.
  • afterEach() – this runs after every individual test cases.
  • before() – runs before all the tests in the spec file.
  • beforeEach() – executes before each individual test cases.

How to write a test case?

Before we begin, we should know what a test case is, write it, and what the steps are for a basic test case.

1. Pre-requisite – The state of the application that we are going to test.

2. Action – We perform some action on the application.

3. Assertion – We assert or validate the changed behavior concerning our actions.

We will consider LamdaGeeks application for our test examples. With the same procedure, we will consider automating the following scenario

1. Visit the website https://lambdageeks.com/

2. Validate whether the title is Home – Lambda Geeks
Cypress uses cy as its type definition. We will be appending the cy command to invoke any methods.
Firstly, let’s create a new file in our code editor.

1. Create a new folder named Demo under the integration folder.

Creation of new folder

2. Under the Demo folder, create a new file sample.js. We will write our first test case in this file.

Creation of new file

Now let us commence writing our test cases!

1. 1. Firstly, we will visit the page using the visit() method in Cypress. This command will navigate to the URL that we provide. We will encompass them inside a describe() and it() block.

//type definition for Cypress object 'cy'
/// <reference types="cypress" />

describe("Testing the application", function() {
    it("launch the application", function() {
        // visit the lambdageeks page
        cy.visit('https://lambdageeks.com/')

2. Once the application is open, we will validate the title using the get() method in Cypress .get() fetches all the css selectors from the DOM.

We are accessing the title using the title() method, and we are asserting using the Chai library with the command should by passing the first parameter as equal, in short eq. The second parameter is the string which we are expecting.

 cy.title().should('eq','Home - Lambda Geeks')

Hurray! With two simple steps, we have written our Cypress Test case.

Here is the complete code of our test case

//type definition for Cypress object 'cy'
/// <reference types="cypress" />

describe("Testing the application", function() {
    it("launch the application", function() {

        // visit the lambdageeks page
        cy.visit('https://lambdageeks.com/')

        // validate the title
        cy.title().should('eq','Home - Lambda Geeks')
       
    });
});
Cypress Example: First test case

Cypress Login Example

We will see examples of how to automate a login page using Cypress. As we saw before, writing a test case in Cypress is simple. Now let us jump into setting the values in the text field and assertions.

1. We visit the website https://demo.applitools.com/ by using cy.visit command.

 cy.visit('https://demo.applitools.com/')

2. Enter username in the username field using type command. We will be passing the username as a string in the type as a parameter.

 cy.get('#username').type('test123')

3. Similarly, we write the same command to enter the password

 cy.get('#password').type('123')

4. Now, we click the login button using the click() method in Cypress.

cy.get('#log-in').click();

5. After logging in, we land on the app page. So we assert that the URL has the /app extension using the .include() keyword in chai. The first parameter of should is the keyword we are asserting, and the second parameter is the expected result.

cy.url().should('include', '/app')

We have written a complete code for a login functionality in five simple steps. Below is the complete code for your reference.

//type definition for Cypress object 'cy'
/// <reference types="cypress" />

describe("Testing the application", function() {
    it("should login with username and password", function() {

        // visit the lambdageeks page
        cy.visit('https://demo.applitools.com/')

        cy.get('#username').type('test123')

        cy.get('#password').type('123')

        cy.get('#log-in').click();

        cy.url().should('include', '/app')

    });
});
Login Test Case

Solutions to Common Problems while Launching Cypress & FAQ

There might be some common problems we will face when we are trying to launch Cypress. We will discuss some of the common issues.

1. Cannot find ‘Cypress’ command during Open Cypress command

Once after installation, we should pass the open cypress command from the root of the project directory. For instance, you have created a project named CypressProject; you should pass the npm init command by navigating to the CypressProject folder. You can navigate by giving the below command in the terminal

cd CypressProject

Once you are at the root of the project, then pass the npm init command to download the dependencies.

Now to open Cypress, some people try to navigate to the /node_modules folder and ./bin and then pass the cypress open command. However, it does not work this way. So instead, give the whole open command from the root of the project directory to open Cypress.

./node_modules/.bin/cypress open

Also, be cautious about the slash ‘/’. Always provide this ‘/’ to open Cypress.

2. Cypress cannot be loaded because running scripts is disabled on this system

When you are installing Cypress in windows, you might sometimes face the above error. It is because due to a security exception. We can solve this error by passing the below command in PowerShell.

Set-ExecutionPolicy RemoteSigned

Steps to reproduce:

  • Open PowerShell
  • Run this command Set-ExecutionPolicy RemoteSigned
  • Type Yes
  • Now open the Cypress by passing ./node_modules/.bin/cypress open. Test Runner will open now.

FAQ

1. Which are the operating systems supported by Cypress?

Cypress supports Mac, Windows, and Linux operating systems.

2. Does Cypress support automation in native mobile apps?

Cypress will not be able to run on a native mobile app ever. But we can test mobile applications that are written in a browser like Iconic Frameworks.

3. Whether Cypress supports only Javascript-based applications?

No! Cypress can interact with any web browser written in languages like Ruby on Rails, Node, PHP, C#. But we will be writing our tests in Javascript. Otherwise, Cypress can interact with any front end, back end, language, and framework.

Aishwarya Lakshmi

I am a testing enthusiast and have nearly 2+ years of experience in the testing domain. I am passionate about testing and love to explore new things in my field and share them with my peers. I enjoy writing blogs during my free time in the simplest but effective way. As a tester, I like to have things to perfection, so I wish my readers to have the perfect understanding of the technology. I keep myself updated with the new technologies related to testing and spend time understanding them. I am glad to help students understand the concepts in testing. Let's connect through LinkedIn - https://www.linkedin.com/in/aishwarya-lakshmi-n-46903217a

Recent Posts