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!
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 LambdaTest Now!
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 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 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:
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 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:
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:
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 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:
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 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.
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 |
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'
}
})
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.
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.
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 : 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.
Cypress provides a variety of assertions that can be used to ensure that tests are functioning as expected.
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.
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.
On this page
Did you find this page helpful?
Try LambdaTest Now !!
Get 100 minutes of automation test minutes FREE!!