• Automation
  • Home
  • /
  • Learning Hub
  • /
  • What are Cypress Assertions: Complete Tutorial
  • -
  • April 27 2023

What are Cypress Assertions: Complete Tutorial

This Cypress tutorial deep dives into various Cypress assertions used while performing automation testing.

OVERVIEW

Cypress is a popular test automation framework for web applications. It allows developers to write and run tests for their applications and to validate that the tests are functioning as expected. One of the key features of Cypress is its built-in assertions library, which allows developers to write tests that validate the behavior of their application.

Assertions are statements that verify the expected outcome of a test. In Cypress, assertions are used to check the state and behavior of the application under test. The Cypress assertions library provides a variety of assertion methods that can be used to test various aspects of your application.

This Cypress tutorial deep dives into various Cypress assertions used while performing automation testing. If you want to upscale your Cypress knowledge further. Head over to our Cypress Interview Questions for a curated list of questions and solutions.

So, let’s get started!

What are Assertions?

Assertions are a piece of code that any testing library provides. Test libraries such as Chai and Jest provide a range of assertion methods that can be used to evaluate different types of values or behaviors in the code.

Typically, assertions return a Boolean value, indicating whether a particular condition is true or false to know whether the test has passed. Using assertions, developers can quickly and accurately identify bugs or errors in their code and ensure that their software functions as intended.

Assertions are a crucial part of the testing process, as they determine whether a test has passed or failed based on its successful functionality.

Without assertions, we won’t be able to determine if the test has produced the expected output or if any errors or issues need to be addressed.

In this Cypress assertions tutorial, we will explore the different types of assertions available in Cypress and how to use them effectively in your tests.

One of the key features of Cypress automation tool is its assertion library, Chai. This library provides many functions for writing assertions, including expect and should.

These functions allow developers to write assertions in a behavior-driven development (BDD) style, using given-when-then scenarios to describe the expected behavior of their tests.

We will also explore TDD assertions, Chai-jQuery assertions, and finally Sinon-Chai assertions, their importance, and when to use them.

Note

Note : Run Cypress Tests Online. Try LambdaTest Now!

Types of Cypress Assertions

Assertions in Cypress verify that the application behaves as expected. They play a crucial role in ensuring the accuracy and stability of web applications.

Subscribe to our LambdaTest YouTube Channel to get the latest updates on tutorials around Selenium testing, Cypress testing, Appium, and more.

Some common types of Cypress assertions include:

  • BDD (Behavior-Driven Development) assertions
  • BDD assertions are written using the expect and should functions, as described above.

  • TDD (Test-Driven Development) assertions
  • TDD assertions, on the other hand, are written using the assert function.

  • Chai-jQuery assertions
  • Chai-jQuery assertions combine Chai and jQuery and allow developers to use jQuery selectors to locate elements on the page and make assertions about their state.

  • Sinon-Chai assertions
  • Sinon-Chai assertions is a powerful assertion library that can be used with the Cypress testing framework. It provides a simple and expressive syntax for making assertions about the behavior of test stubs and spies in Cypress.

This Cypress assertions tutorial will look at each type of assertion and provide examples of using them while performing Cypress test automation. We will start with BDD assertions and then move on to TDD, Chai-jQuery, and Sinon-Chai assertions.

...

BDD Assertions in Cypress

BDD assertions are written in style known as "Given-When-Then," which describes the behavior of a feature or scenario in natural language. In Cypress, you can write BDD assertions using the expect and should function.

Here is an example of using the expect function to make a BDD assertion in Cypress:


describe("Todo List", () => {
  beforeEach(() => {
    cy.visit("https://lambdatest.github.io/sample-todo-app/")
  })


  it("Should have the correct text for first item", () => {
    cy.get("li").first().find("span").then((el) => {
        expect(el.text()).to.equal("First Item")
    })
  })


  it("Should have the correct text for remaining count", () => {
    cy.get(".ng-binding").then((el) => {
        expect(el.text()).to.equal("5 of 5 remaining")
    })
  })


  it("Should add new item to the list", () => {
    cy.get("#sampletodotext").type("New Item")
    cy.get("#addbutton").click()
    cy.get("li").last().find("span").then((el) => {
        expect(el.text()).to.equal("New Item")
    })
  })
})

And here is an example of using the should function to make the same assertion:


describe("Todo List", () => {
  beforeEach(() => {
    cy.visit("<https://lambdatest.github.io/sample-todo-app/>")
  })


  it("Should have the correct text for first item", () => {
    cy.get("li").first().find("span").should("have.text", "First Item")
  })


  it("Should have the correct text for remaining count", () => {
    cy.get(".ng-binding").should("have.text", "5 of 5 remaining")
  })


  it("Should add new item to the list", () => {
    cy.get("#sampletodotext").type("New Item")
    cy.get("#addbutton").click()
    cy.get("li").last().find("span").should("have.text", "New Item")
  })
})

Here are some other examples of popular BDD assertions in Cypress:

  • Asserting that an element has a specific class:
  • cy.get("#some-element").should("have.class", "some-class")
  • Asserting that an element is visible:
  • cy.get("#some-element").should("be.visible")
  • Asserting that an element is hidden:
  • cy.get("#some-element").should("be.hidden")

You can also chain multiple Cypress assertions together using the should function and the and function. This allows you to test multiple aspects of an element or feature in one go, validating the tested system more thoroughly.

Here is an example of chaining multiple Cypress assertions together using the should and and functions:


cy.get("#some-element").should("be.hidden")

This example uses the should function to start the chain of assertions, and the and function to add additional assertions to the chain, if any of these assertions fail, the test will fail.


ScenarioExample using should()Example using expect()
Asserting expected text/number equals to actual text/numbercy.get("selector"). should("have.text", "expectedText")expect("expectedText").to.have .text("actualText")
Asserting two objects with validating every property and its valuecy.wrap(someObject). should("deep.equal", {name: "expectedName", age: expectedAge})expect(someObject) .to.deep.equal({name: "expectedName", age: expectedAge})
Asserting the data type of the actual valuecy.get("h1").invoke ("text").should("be.a", "string")expect("value").to.be.a("string")
Asserting expected value is greater than actual valuecy.get("selector"). invoke("text").then(parseInt). should("be.greaterThan", expectedValue)expect(intValue).to.be. greaterThan(expectedValue)

TDD Assertions in Cypress

TDD assertions are mostly written in style known as "Arrange-Act-Assert," which describes the steps of a test in a logical order. In Cypress, you can use the assert function to write TDD assertions.

What is the Arrange-Act-Assert (AAA) pattern?

Arrange-Act-Assert (AAA) is a pattern for writing test code often used in Test-Driven Development (TDD).

The AAA pattern consists of three steps:

  • Arrange: Set up the necessary preconditions and inputs for the test.
  • Act: Perform the action being tested.
  • Assert: Verify that the expected outcome has occurred.

The AAA pattern helps to structure test code in a way that is easy to understand and maintain. It also helps to ensure that tests are independent and self-contained, as each test should follow the same basic structure and not depend on the system's state from previous tests.

Here is an example of using the assert function to make a TDD assertion in Cypress:


describe("My Feature", () => {
  it("should do something", () => {
    // Arrange
    cy.visit("<http://example.com>");
    cy.get("#input").type("hello");


    // Act
    cy.get("#submit").click();


    // Assert
    cy.get("#output").then(output => {
      assert.equal(output.text(), "hello");
    });
  })
})

This example visits a website and retrieves the text of an element with the ID of "#some-element", then uses the assert.equal function to assert that the text equals the "Expected Text".

Here are some other examples of popular TDD assertions in Cypress:

  • Asserting that an element has a specific class:
  • cy.get("#some-element").then(($el) => {
      assert.isTrue($el.hasClass("some-class"))
    })
  • Asserting that an element is visible:
  • cy.get("#some-element").then(($el) => {
      assert.isTrue($el.is(":visible"))
    })

    Since the return value of the get function is a jQuery object, it can be used with any jQuery functions or methods. In this case, the is function is used to check if the element is visible using the :visible selector.

    The is function is a jQuery function that returns a boolean value indicating whether the element matches the selector.

    In the callback function, the result of the is function is passed to the assert.isTrue function, which checks that the element is indeed visible. If the assertion fails, the test will fail.

  • Asserting that an element is hidden:
  • cy.get("#some-element").then(($el) => {
      assert.isTrue($el.is(":hidden"))
    })
  • Asserting that an element has a specific attribute:
  • cy.get("#some-element").then(($el) => {
      assert.equal($el.attr("type"), "text")
    })

Here is a list of examples of using the TDD approach with Cypress:


ScenarioExample
Asserting expected text equals actual textassert.equal(value, "hello")
Asserting expected text is contained in actual textassert.include(value, "hello")
Asserting expected value equals actual valueassert.strictEqual(value, 5)
Asserting expected value is greater than actual valueassert.isAbove(value, 4)
Asserting expected value is less than actual valueassert.isBelow(value, 6)
Asserting expected value is within a range of actual valueassert.isAtLeast(value, 4)
Asserting expected value is above or equal to actual valueassert.isAtMost(value, 6)
Asserting expected value is below or equal to actual valueassert.isTrue(value <= 6)
Asserting expected value is truthyassert.isOk(value)
Asserting two objects are deeply equalassert.deepEqual(obj1, obj2)
Asserting expected value is an objectassert.isObject(value)
Asserting expected value is a certain typeassert.typeOf(value, "string")

These Cypress assertions can help make various types of checks about the state of your application in Cypress.

Chai-jQuery Assertions in Cypress

Chai-jQuery assertions are a combination of Chai and jQuery, allowing you to use jQuery selectors to locate elements on the page and make assertions about their state.

An example of using Chai-jQuery assertions in Cypress is as follows:


cy.visit("<https://www.example.com/>")
cy.get("#favorites").should(($el) => {
  expect($el).to.have.css("color", "red")
  expect($el).to.have.css("font-size", "20px")
})

In this example, we visit a website and use a jQuery selector to locate an element with the ID of "favorites". We then use the should function to make two Cypress assertions about the element's CSS properties: that its color is red and its font size is 20px.

Other examples of popular Cypress assertions that can be used with Chai-jQuery include:

  • Asserting that an element has a specific class:
  • cy.get("selector").should(($el) => {
      expect($el).to.have.class("some-class")
    })
  • Asserting that an element is visible:
  • cy.get("selector").should(($el) => {
      expect($el).to.be.visible
    })
  • Asserting that an element is hidden:
  • cy.get("selector").should(($el) => {
      expect($el).to.be.hidden
    })
  • Asserting that an element has a specific attribute:
  • cy.get("selector").should(($el) => {
      expect($el).to.have.attr('font-family', 'Arial')
    })

These are just a few examples of the types of Cypress assertions that can be made using Chai-jQuery.

Here is a table of some of the most commonly used Chai-jQuery assertions, with examples:


ScenarioExample
Assert that an element has a certain CSS classcy.get('#element').then($el => expect($el).to.have.class('class-name'))
Assert that an element has a certain attributecy.get('#element').then($el => expect($el).to.have.attr('attribute-name'))
Assert that an element is visiblecy.get('#element').then($el => expect($el).to.be.visible)
Assert that an element is hiddency.get('#element').then($el => expect($el).to.be.hidden)
Assert that an element has a certain textcy.get('#element').then($el => expect($el).to.have.text('some text'))
Assert that an element has a certain valuecy.get('#element').then($el => expect($el).to.have.value('some value'))
Assert that an element contains a certain textcy.get('#element').then($el => expect($el).to.contain('some text'))
Assert that an element is emptycy.get('#element').then($el => expect($el).to.be.empty)
Assert that an element has a certain lengthcy.get('#element').then($el => expect($el).to.have.length(3))
Assert that an element is disabledcy.get('#element').then($el => expect($el).to.be.disabled)

Sinon-Chai Assertions in Cypress

Sinon-Chai is a powerful assertion library that can be used in conjunction with the Cypress UI automation framework.

One of the key features of Cypress is its ability to easily create and manage test stubs and spies, which can be used to simulate the behavior of external dependencies in a controlled environment.

Here are a few examples of how to use Sinon-Chai assertions in Cypress:

Assert that a test stub has been called a certain number of times:


const obj = {
  myMethod() {
    console.log("hello world")
  },
}


cy.stub(obj, "myMethod")


obj.myMethod()
obj.myMethod()
obj.myMethod()
obj.myMethod()
obj.myMethod()


expect(obj.myMethod).to.have.callCount(5)

Assert that a spy has been called with specific arguments:


const obj = {
  myMethod(arg1: string, arg2: string) {
    console.log(arg1, arg2)
  },
}


const arg1 = "hello", arg2 = "world"


cy.spy(obj, "myMethod")


obj.myMethod(arg1, arg2)


expect(obj.myMethod).to.have.been.calledWith(arg1, arg2)

Assert that a test stub has not been called:


const obj = {
  myMethod(arg1: string, arg2: string) {
    console.log(arg1, arg2)
  },
}


cy.stub(obj, "myMethod")


expect(obj.myMethod).to.not.have.been.called

Assert that a spy has been called on a specific object:


const spy = cy.spy()
const obj = { method: spy }
obj.method()
expect(spy).to.have.been.calledOn(obj)

Assert that a test stub has been called with a specific value:


const obj = {
  myMethod(...args: any) {
    console.log(args)
  },
}


cy.spy(obj, "myMethod")


obj.myMethod({ name: "John" })


expect(obj.myMethod).to.have.been.calledWith({ name: "John" })

Assert that a spy has been called before another spy:


const spy1 = cy.spy()
const spy2 = cy.spy()
spy1()
spy2()
expect(spy1).to.have.been.calledBefore(spy2)

These examples demonstrate how Sinon-Chai assertions can be used in Cypress to test the behavior of test stubs and spies. Using the cy.stub()and cy.spy() methods, you can create and manage test stubs and spies and then use Sinon-Chai to assert their behavior.


ScenarioExample
Assert that a test stub has been called a certain number of timesexpect(stub).to.have.callCount(4)
Assert that a spy has been called with specific argumentsexpect(spy).to.have.been.calledWith(arg1, arg2)
Assert that a test stub has not been calledexpect(stub).to.not.have.been.called
Assert that a spy has been called on a specific objectexpect(spy).to.have.been.calledOn(obj)
Assert that a spy has been called before another spyexpect(spy1).to.have.been.calledBefore(spy2)
Assert that a spy has been called after another spyexpect(spy1).to.have.been.calledAfter(spy2)
Assert that a spy has been called at least a certain number of timesexpect(spy).to.have.been.called.at.least(5)
Assert that a test stub has been called only onceexpect(stub).to.have.been.calledOnce

Real-Life Examples of Running Cypress Tests

Now it’s time to use what we’ve learned on a website and execute some Cypress tests.

For that, we’ll need a running website to run our tests on. Here, we’ll use this eCommerce website to run our tests on.

You can set your baseUrl property in the cypress.config.js file to the website. This makes it easier for us to navigate through the website.


const { defineConfig } = require('cypress')


module.exports = defineConfig({
  e2e: {
    baseUrl: 'https://ecommerce-playground.lambdatest.io'
  }
})

Running BDD Assertions with Cypress

In this example, we’re running a few BDD assertions on the header component of the website and see if it passes the tests.


describe("Header component", () => {
  beforeEach(() => {
    cy.visit("/")
  })


  it("should display the logo with the right dimension values", () => {
    cy.get("#main-header")
      .find(".entry-design.design-image figure a img")
      .should("have.attr", "alt", "Poco Electro")
      .and("have.attr", "height", "50")
  })
  it("should display the correct text for the search category dropdown", () => {
    cy.get("#main-header")
      .find(".entry-widget.widget-search .dropdown-toggle")
      .should("have.text", "All Categories")
  })


  it("should display the correct placeholder text for the search input", () => {
    cy.get("#main-header")
      .find('.entry-widget.widget-search input[name="search"]')
      .should("have.attr", "placeholder", "Search For Products")
  })
})
LambdaTest

As you can see we are using cy.visit('/') because we have set the baseUrl of our website in the cypress.config.js before.

In the first test, we use the .find() method to find the img element that we want to run the tests on, and we use the .should() method to run the actual assertion.

We use the .and() method to chain another extra assertion on the same img element.

Running TDD Assertions with Cypress

Let’s write some tests for TDD assertions in Cypress.


describe("Header Tests", () => {
  beforeEach(() => {
    cy.visit("/")
  })


  it("Logo is visible and links to the homepage", () => {
    cy.get("#entry_217821 a").then(($logoLink) => {
      assert.strictEqual(
        $logoLink.attr("href"),
        "https://ecommerce-playground.lambdatest.io/index.php?route=common/home"
      )
      assert.strictEqual($logoLink.attr("title"), "Poco Electro")
    })


    cy.get("#entry_217821 img").then(($logoImg) => {
      assert.strictEqual($logoImg.attr("alt"), "Poco Electro")
    })
  })


  it("Search bar is visible and functional", () => {
    cy.get('#search input[type="text"]').then(($searchInput) => {
      assert.strictEqual(
        $searchInput.attr("placeholder"),
        "Search For Products"
      )
    })


    cy.get('#search button[type="submit"]').then(($searchBtn) => {
      assert.strictEqual($searchBtn.text().trim(), "Search")
    })
  })
})

In the first test, we are using the assert.strictEqual() method to assert that the href attribute of the a element equals a specific value.

By using assert in our Cypress tests, we are incorporating assertions that focus on the expected output and behavior of various elements within the application, which helps ensure that the end-to-end (E2E) user experience meets the desired specifications and performs as expected.

Running Chai-jQuery Assertions with Cypress

Now, let's write more tests with some Chai-jQuery assertions.


describe("Article Thumbnail", () => {
  beforeEach(() => {
    cy.visit("/index.php?route=extension/maza/blog/home")
  })


  it("displays the correct image", () => {
    cy.get(".article-thumb .image img")
      .first()
      .then(($image) => {
        expect($image).to.have.attr("width", "420")
      })
  })


  it("displays the correct title", () => {
    cy.get(".title")
      .first()
      .then(($title) => {
        expect($title).to.have.css("color", "rgb(0, 0, 0)")
      })
  })


  it("button should have correct height and width", () => {
    cy.get(".icon.svg-icon").then(($icon) => {
      expect($icon).to.have.attr("style", "width:20px;height:20px;")
    })
  })
})

In the first example, we are getting the image element of a thumbnail of one of the articles, we are using the first() method to get the first element of the returned array of objects.

We are also using the .then() callback function to access the returned jQuery element, which will be in the first argument of the callback function. In this case, the $image argument is the returned jQuery element.

We then pass the jQuery element to the expect() function and run the assertions on that element. In the first test, we assert that the image width should be 420 pixels.

To ensure reliable testing, performing tests on the cloud across real browsers and OS is essential, as this will lead to more accurate results. Testing the application under real user conditions helps to detect performance issues that may impact user experience, allowing for timely fixes before release. By leveraging cloud-based digital experience testing platforms like LambdaTest, you can perform Cypress end-to-end testing more quickly and effectively on over 50+ real browsers and OS combinations.

Note

Note : Here is our support documentation to help you get started with Cypress testing.

You can further accelerate your software release cycle by performing Cypress parallel testing across browsers like Chrome, WebKit, Electron, etc., on a scalable Cypress Cloud.

If you are a developer or a tester seeking to improve your test automation abilities by learning Cypress, LambdaTest offers the Cypress 101 certification, which is ideal for both novice and experienced users. This certification is tailored to teach the fundamentals of Cypress and how to employ it to create automated tests for web applications.

Conclusion

Cypress provides a variety of assertions that can be used to ensure that tests are functioning as expected.

  • BDD assertions, written using the expect and should functions, provide a natural language style for describing the behavior of a feature or scenario
  • TDD assertions, on the other hand, are written using the assert function.
  • Chai-jQuery assertions allow developers to use jQuery selectors to locate elements on the page and make assertions about their state.
  • Sinon-Chai assertions provide a simple and expressive syntax for making assertions about the behavior of test stubs and spies in Cypress.

Each of these Cypress assertion types can be used to validate the functionality of your tests in Cypress effectively. You can learn more about some tips & tricks through the hub on cypress tips and tricks.

About author

Dawson is a full-stack developer, freelancer, content creator, and technical writer. He has more than three years of experience in software engineering, and he is passionate about building projects that can help people. You can also follow him on Twitter.

Frequently asked questions

  • General ...
What are the assertions in Cypress?
In Cypress, assertions are used to verify the application's state under test. Assertions are used to ensure certain conditions are met during a test. Cypress provides several built-in assertions that you can use in your tests.
What is the difference between assert and expect in Cypress?
Both assert and expect are used for assertions in Cypress, but they have different syntax and behavior. The assert method in Cypress is a Chai assertion method used to assert that a value meets a certain condition. For example, you can use the assert method to verify that a certain element exists on the page or that a certain value is equal to a specific value. On the other hand, the expect method in Cypress is also a Chai assertion method, but it is used to assert that a value meets a certain condition and returns a value.
Does Cypress add automated waits for assertions?
Yes, Cypress automatically adds implicit waits for assertions in your tests. When you use a Cypress command like cy.get() or cy.contains(), Cypress waits for the element to be available on the page before executing any assertions. This means you don't need to explicitly add any waits to your tests to ensure that the page has loaded or that the element is visible before making assertions.
Which command is used for implicit assertion in Cypress?
There is no specific command for the implicit assertion in Cypress, as all Cypress commands include an implicit assertion that ensures the element exists and is in the expected state before proceeding with the test.For example, when you use the cy.get() command to select a DOM element, Cypress automatically waits for the element to be available on the page and then asserts that it exists and is visible. If the element is not found or visible, the command will fail, and the test will stop.

Did you find this page helpful?

Helpful

NotHelpful

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud