Power Your Software Testing with AI Agents and Cloud
The Native AI-Agentic Cloud Platform to Supercharge Quality Engineering. Test Intelligently and Ship Faster.
- TestMu AI (Formerly LambdaTest)
- /
- Learning Hub
- /
- A Complete Guide To Cypress Assertions
A Complete Guide To Cypress Assertions
This Cypress tutorial deep dives into various Cypress assertions used while performing automation testing.
Last Updated on:
Cypress assertions are the checks that confirm a test's actual result matches what a page or application should show, using Chai, Sinon-Chai, and jQuery-Chai libraries under Cypress's own retry logic.
Cypress retries a .should() or .and() assertion for up to 4 seconds by default before failing, unlike a plain Chai expect() outside a chain, which runs only once.
This guide covers assertion types, BDD, TDD, Chai-jQuery, and Sinon-Chai syntax, how Cypress retries assertions today, and real test examples.
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: Run Cypress Tests Online. Try TestMu AI 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 TestMu AI 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
- TDD (Test-Driven Development) assertions
- Chai-jQuery assertions
- Sinon-Chai assertions
BDD assertions are written using the expect and should functions, as described above.
TDD assertions, on the other hand, are written using the assert function.
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 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")cy.get("#some-element").should("be.visible")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.
| Scenario | Example using should() | Example using expect() |
|---|---|---|
| Asserting expected text/number equals to actual text/number | cy.get("selector"). should("have.text", "expectedText") | expect("expectedText").to.have .text("actualText") |
| Asserting two objects with validating every property and its value | cy.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 value | cy.get("h1").invoke ("text").should("be.a", "string") | expect("value").to.be.a("string") |
| Asserting expected value is greater than actual value | cy.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"))
})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.
cy.get("#some-element").then(($el) => {
assert.isTrue($el.is(":hidden"))
})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:
| Scenario | Example |
|---|---|
| Asserting expected text equals actual text | assert.equal(value, "hello") |
| Asserting expected text is contained in actual text | assert.include(value, "hello") |
| Asserting expected value equals actual value | assert.strictEqual(value, 5) |
| Asserting expected value is greater than actual value | assert.isAbove(value, 4) |
| Asserting expected value is less than actual value | assert.isBelow(value, 6) |
| Asserting expected value is within a range of actual value | assert.isAtLeast(value, 4) |
| Asserting expected value is above or equal to actual value | assert.isAtMost(value, 6) |
| Asserting expected value is below or equal to actual value | assert.isTrue(value <= 6) |
| Asserting expected value is truthy | assert.isOk(value) |
| Asserting two objects are deeply equal | assert.deepEqual(obj1, obj2) |
| Asserting expected value is an object | assert.isObject(value) |
| Asserting expected value is a certain type | assert.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")
})cy.get("selector").should(($el) => {
expect($el).to.be.visible
})cy.get("selector").should(($el) => {
expect($el).to.be.hidden
})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:
| Scenario | Example |
|---|---|
| Assert that an element has a certain CSS class | cy.get('#element').then($el => expect($el).to.have.class('class-name')) |
| Assert that an element has a certain attribute | cy.get('#element').then($el => expect($el).to.have.attr('attribute-name')) |
| Assert that an element is visible | cy.get('#element').then($el => expect($el).to.be.visible) |
| Assert that an element is hidden | cy.get('#element').then($el => expect($el).to.be.hidden) |
| Assert that an element has a certain text | cy.get('#element').then($el => expect($el).to.have.text('some text')) |
| Assert that an element has a certain value | cy.get('#element').then($el => expect($el).to.have.value('some value')) |
| Assert that an element contains a certain text | cy.get('#element').then($el => expect($el).to.contain('some text')) |
| Assert that an element is empty | cy.get('#element').then($el => expect($el).to.be.empty) |
| Assert that an element has a certain length | cy.get('#element').then($el => expect($el).to.have.length(3)) |
| Assert that an element is disabled | cy.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.calledAssert 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.
| Scenario | Example |
|---|---|
| Assert that a test stub has been called a certain number of times | expect(stub).to.have.callCount(4) |
| Assert that a spy has been called with specific arguments | expect(spy).to.have.been.calledWith(arg1, arg2) |
| Assert that a test stub has not been called | expect(stub).to.not.have.been.called |
| Assert that a spy has been called on a specific object | expect(spy).to.have.been.calledOn(obj) |
| Assert that a spy has been called before another spy | expect(spy1).to.have.been.calledBefore(spy2) |
| Assert that a spy has been called after another spy | expect(spy1).to.have.been.calledAfter(spy2) |
| Assert that a spy has been called at least a certain number of times | expect(spy).to.have.been.called.at.least(5) |
| Assert that a test stub has been called only once | expect(stub).to.have.been.calledOnce |
How Does Cypress Retry Assertions Today?
Cypress retries .should() and .and() assertions, plus the implicit checks built into action commands like .click(), for up to 4 seconds by default, per Cypress's own retry-ability documentation. A plain Chai expect() outside a Cypress chain, and any assertion inside a .then() callback, run only once and do not retry.
- Queries and .should()/.and() retry: Cypress re-runs the whole command chain until the assertion passes or the timeout elapses, under what Cypress calls retry-ability.
- .then() callbacks do not retry: Code inside .then() executes once, so an assertion written there does not wait for a slow-loading value the way .should() does.
- Default timeout is 4 seconds: Controlled by defaultCommandTimeout, which can be raised globally with cypress run --config defaultCommandTimeout=10000, or overridden for a single command with a timeout option, as shown below.
- A timeout of 0 disables retrying: Useful only when a command must fail immediately instead of pausing for the element to appear.
This distinction matters for flaky tests: wrapping a check in .should() lets Cypress wait out a slow API response or animation, while the same check inside .then() fails immediately if the value has not arrived yet.
// Retries automatically until it passes or the 4-second timeout elapses
cy.get('.status').should('have.text', 'Complete')
// Runs once - does NOT retry, even if the value updates a moment later
cy.get('.status').then(($el) => {
expect($el.text()).to.equal('Complete')
})
// Per-command timeout override
cy.get('.status', { timeout: 10000 }).should('have.text', 'Complete')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")
})
})

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 TestMu AI, you can perform Cypress end-to-end testing more quickly and effectively on over 50+ real browsers and OS combinations.
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, TestMu AI 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.
Author

Dastan
Blogs: 4
Dastan, known online as dcodes, is a full-stack developer and technical writer with several years of experience in software engineering. On TestMu AI (formerly LambdaTest), he authored tutorials on Cypress testing, Cypress best practices, Cypress debugging, Playwright with Cucumber, and Podman versus Docker containerization. He also publishes developer tutorials on his platform dcodes.dev and founded rustfinity.com, a platform for learning the Rust programming language.
Frequently asked questions
Did you find this page helpful?
More Related Learning Hubs
TestMu AI forEnterprise
Get access to solutions built on Enterprise
grade security, privacy, & compliance
- Advanced access controls
- Advanced data retention rules
- Advanced Local Testing
- Premium Support options
- Early access to beta features
- Private Slack Channel
- Unlimited Manual Accessibility DevTools Tests





