What are Cypress Assertions & How to Handle Them?

On This Page What are Cypress Assertions?W

February 21, 2026 · 11 min read · Tool Comparison

What are Cypress Assertions & amp; How to Handle Them?

Tests are effective only when the outcome of the activeness are validated against a set of await results.Cypress provides assertion commandto validate the expected value with actual value and these assertion commands are from a popular library nameChai.

Cypress bundles the chai assertion library and there is no need to install this library.

The assertion involve passing two parameters to the command: expected values and actual values. The assertion command will insure for a specific example and return a boolean value, which will then decide whether the test is passing or failing

What are Cypress Assertions?

Cypress Assertions are essential in the and perfective for. As per the official corroboration, “ Assertions draw the desired province of your elements, your objective, and your application. ”

  • By checking if sure conditions or expectations about your web page are met during a examination, Cypress Assertions help you vouch that your web app behaves correctly.
  • They ensure that your situation & # 8217; s crucial elements and interactions are functioning cleanly.
  • Cypress come bundled with a popular assertion library, using which we can write potent and effective assertions.
  • The reward of using Cypress Assertion is that it rehear the previous chained dictation untildefaultTimeoutis specified.

Below is an example which shew asseveration in cypress

cy.get ('.button ') .should ('exist ') .and ('be.visible ') .and ('have.class ', 'active ');

The instance shows three averment on a button

  • should (& # 8216; exist & # 8217;): This will secure the button be in the DOM
  • and (& # 8216; be.visible & # 8217;): This will ensure the push is seeable in the DOM
  • and (& # 8216; have.class & # 8217;, & # 8216; active & # 8217;): This will ensure the specified family gens exists in the button

What are Inexplicit Assertions in Cypress?

Implicit assertions in Cypress are do automatically without requiring an explicit averment statement in the tryout codification. These implicit assertions get tests more resilient by assure that elements are in the expected province before interacting with them.

Below is an model to explain implicit assertions in Cypress:

cy.get ('input [name= '' firstName ''] ')

The get query bidding, by default, postponement for the element to exist in the DOM and retries for the maximum timeout specified.

What are Explicit Assertions in Cypress?

Explicit assertions give you fine-grained control over your test affirmation and permit you to insure specific conditions important for your test cases. You can use explicit statement to check for specific weather when indite tests in Cypress. Cypress furnish a set of assertion commands for this purpose.

Below is an example to explicate explicit assertions in Cypress:

cy.get ('input [name= '' firstName ''] ') .should (“ be.visible ”)

The getquery bid, by default, waits for the factor to exist. Using explicit assertions such asshould(), it is possible to corroborate whether the element is visible. This approach allows for validating additional conditions on the factor establish on the test scenario, lead to more stable and reliable tests.

Types of Cypress Assertions

Cypress provides a robust set of statement styles to corroborate application behavior during test. These assertions help confirm that the application performs as await by comparing genuine effect with awaited effect.

  1. BDD Assertion
  2. TDD Assertion
  3. Chai-jQuery
  4. Sinon-Chai Assertions in Cypress

Learn More: for initial frame-up

1. BDD Assertions in Cypress

BDD stand for Behavior-Driven Development, where the tests are written according to the User Behavior as Scenarios employGiven, When, and Then.

Chai provideexpect and shouldpart to write statement in a BDD way. Below are the instance of usingexpect() and should()assertions in Cypress.

Using await

cy.visit (`` https: //www.bstackdemo.com/ '') cy.get (`` # favourites strong '') .then (($ el) = & gt; {expect ($ el.text ()) .to.be.eq (`` Favourites '')})

Using should

cy.visit (`` https: //www.bstackdemo.com/ '') cy.get (`` # favourites strong '') .invoke (`` text '') .should (`` be.eq '', `` Favourites '')

Also Read:

Examples of BDD Assertions

Examples of democratic Cypress Assertions for certain scenarios are ply below:

ScenarioExample using should ()Example employ expect ()
Asserting anticipate text/number equals to actual text/numbercy.get (& # 8220; picker & # 8221;) .should (& # 8220; have.text & # 8221;, & # 8220; AutomationTester & # 8221;)expect (& # 8220; expectedText & # 8221;) .to.have.text (& # 8220; actualText & # 8221;)
Asserting two objects with validating every place and its valuecy.get (someObject) .should (& # 8220; deep.equal & # 8221;, {name: & # 8220; AutomationTester & # 8221;, age: 30})look (someObject) .to.deep.equal ({gens: & # 8220; AutomationTester & # 8221;, age: 30})
Asserting the data type of the literal valuecy.get (& # 8220; chooser & # 8221;) .invoke (& # 8220; text & # 8221;) .should (& # 8220; be.a & # 8221;, & # 8220; string & # 8221;)expect (& # 8220; value & # 8221;) .to.be.a (& # 8220; draw & # 8221;)
Asserting ask value is great than actual valuecy.get (& # 8220; selector & # 8221;) .invoke (& # 8220; text & # 8221;) .then (parseInt) .should (& # 8220; be.greaterThan & # 8221; ,20)expect (intValue) .to.be.greaterThan (8)
Asserting length of elementscy.get (& # 8220; picker & # 8221;) .should (& # 8220; have.length & # 8221; ,3)require (someValue) .to.have.length (3)
Assert element is visiblecy.get (& # 8220; selector & # 8221;) .should (& # 8220; be.visible)require (element) .to.be.visible
Assert checkbox is insurecy.get (& # 8220; selector & # 8221;) .should (& # 8220; be.checked & # 8221;)expect (element) .to.be.checked
Assert whether button is disabledcy.get (& # 8220; picker & # 8221;) .should (& # 8220; be.disabled & # 8221;)expect (element) .to.be.disabled

You can also add multiple assertions chained for better proof as seen in the bid below

cy.get (`` selector '') .should (`` have.class '', '' products-found '') .and (`` be.visible '')

The complete listing of Chai ’ s BDD averment can be foundhere

2. TDD Assertions in Cypress

TDD Assertion is possible habituateassert unchanging form bundled inwardly Cypress.

Usage in Cypress is as below

cy.visit (`` https: //www.bstackdemo.com/ '') cy.get (`` .products-found duad '') .then (($ el) = & gt; {assert.equal (`` 0 Product (s) institute. ``, $ el.text (), `` Product Text institute. '')})

Examples of TDD Cypress Assertions

ScenarioExample
Assert if object is truthy (Ensures object is not undefined or null)assert.isOk (object, & # 8216; Validate object is truthy & # 8217;)
Assert if two objects are adequateassert.equal (& # 8220; 0 Product (s) found. & # 8221;, $ el.text (), & # 8220; Product Text found. & # 8221;)
Assert if two objects are equal with all they key are value are matchingassert.deepEqual ({gens: & # 8220; User1 & # 8221;, Age: 26}, {name: & # 8220; User1 & # 8221;, Age: & # 8220; 26 & # 8221;}), & # 8220; This averment will fail as the Age value in second objective is string & # 8221;)
Assert if the given value is an Objectassert.isObject ({name: & # 8220; user1, age: 26}, & # 8220; Check if the value is object & # 8221;)
Assert if the give value is greater than expect valueassert.isAbove (6,1, & # 8220; Check if 6 is outstanding than 1 & # 8221;)
Assert if the yield value go to a specific Data caseassert.typeOf (& # 8220; user1 & # 8221;, & # 8220; draw & # 8221;, & # 8220; Check if the value is of type string & # 8221;)

The consummate listing of Chai ’ s TDD assertion can be basehere

For autonomous testing across multiple user personas, check out SUSATest — it explores your app like 10 different real users.

3. Chai-jQuery Cypress Asserts

This affirmation is helpful when we need to formalize DOM elements and is usually used within thethen() method of Cypress. This is becausethen()method will give the jquery element.

Below is the representative of using Chai-jQuery assertion in the Cypress test

cy.visit (`` https: //www.bstackdemo.com/ '') cy.get (`` .products-found span '') .then (($ el) = & gt; {expect ($ el) .to.have.text (`` 0 Product (s) base. '')})

Democratic Chai-jQuery assertions in Cypress

ScenarioExample
Assert if attribute exists in the given elementexpect ($ el) .to.have.attr (& # 8220; href & # 8221;, & # 8220; /offers & # 8221;)
Assert if element is visiblerequire ($ el) .to.be.visible
Assert if constituent is enabledawait ($ el) .to.be.enabled
Assert if element contains partial textexpect ($ el) .to.contain (& # 8220; Favourite & # 8221;)
Assert if the factor checkbox is insurewait ($ el) .to.be.checked

The complete list of Chai-jQuery assertions can be foundhere

4. Sinon-Chai Assertions in Cypress

The Chai asseveration library cater support for Sinon.js assertions through the Sinon-Chai plugin. Sinon-Chai assertions are useful when using spies and nub (spies are used for inspection, and stub are used for mocking) in Cypress examination to validate weather on the objects being sight on or stub.

Cypress by default comes with sinon-chai assertion instal.

Example:

describe ('Example for sinon assertion ', () = & gt; {it ('validate the method is called on the spy object ', () = & gt; {// Create a Sinon spyconstlogSpy = cy.spy (console, 'log '); // Trigger the method console.log ('Message from console '); // Assert the spy was called expect (logSpy) .to.be.calledOnce; expect (logSpy) .to.be.calledWith ('Message from console ');});});

In the example above, the methodlog,which is used for printing messages to the console, is being spied on:

constlogSpy = cy.spy (console, 'log ')

After the spy begins heed to the method & # 8217; s invocation, theconsole.logmethod is called to print a message:

console.log ('Message from console ');

The number of times theconsole.logmethod was evoke and the message it was invoked with can then be asserted and verified.

expect (logSpy) .to.be.calledOnce; expect (logSpy) .to.be.calledWith ('Message from console ');

Common Cypress Assertions

Below is the categorized summary of unremarkably apply affirmation

DOM Assertion:

cy.get (& lt; chooser & gt;) .should (`` be.visible '')
cy.get (& lt; selector & gt;) .should (`` have.class '')
cy.get (& lt; selector & gt;) .should (`` have.text '')
cy.get (& lt; selector & gt;) .should (`` not.be.visible '')
cy.get (& lt; selector & gt;) .should (`` be.checked '')
cy.get (& lt; selector & gt;) .should (`` have.value '', `` myValue '')

API Assertion:

cy.request ('/api/users ') .its ('body ') .should ('have.property ', 'message ') .and ('be.an ', 'array ');

Spy/Stub Assertion:

expect (logSpy) .to.be.called;
wait (logSpy) .to.be.calledOnce;
expect (logSpy) .to.be.calledWith ('Check sinon instance ');

Talk to an Expert

When Not to Assert in Cypress

While Cypress provides a comprehensive set of assertions, it is crucial to understand the implicit assertions that Cypress performs by default to avoid adding unnecessary explicit assertions.

To execute a click action in Cypress, the following code can be used:

cy.get (`` button '') .click ()

In the above code

  • The get () bidding will assure for the element to exist in DOM
  • The dog command will look for the button to become actionable.

With these built-in chit, there is no motivation to add explicit assertions for element world or visibleness, as they would be redundant.

Why choose existent devices to run Cypress Assertion tests?

Running Cypress assertion tests on existent devices ensures your covering behaves as expected under real-world conditions, not just in imitation environments.

Here & # 8217; s why it count:

  • Accurate Testing Across Browsers & amp; Devices: Emulators can miss edge cases. Existent device ponder true exploiter experiences, including layout shifts, gestures, and hardware limitations.
  • Catch Real-World Bugs Early: Validate visibility, responsiveness, and API behavior on actual device hardware, critical for mobile-first applications.
  • Cross-Platform Confidence: Ensure your affirmation (like.should (& # 8216; be.visible & # 8217;) or .should (& # 8216; have.text & # 8217;))hold true across various OS versions and screen sizes.

ply a scalable, cloud-based substructure to run Cypress tryout on 3500+ real browser and devices, enabling:

  • Zero Setup: No device lab maintenance—start testing instantly.
  • : Run tests faster across multiple device and browsers.
  • Integration: Seamlessly plug into your pipelines like Jenkins, GitHub Actions, or Azure.
  • Detailed Debugging: Get video recordings, log, and screenshots for every asseveration failure.

Conclusion

In this clause, you have realise the panoptic assertion types that Cypress provides that can be employ to write Cypress Automation tests with reliable validations. These Cypress Assertions will give decent assurance that a lineament works functionally without any issues.

  • Unlike early Test Automation tools, in Cypress, if you use theshould()command for an assertion, this command will occupy fear of retrying without adding any extra logic.
  • This will reduce the flakey test part and provide stable exam.
  • can leverage the powerful cloud program provided by BrowserStack Automate to run exam faster and more efficiently.

To maximize the accuracy and dependableness of your Cypress tests, run them on real devices using. It enables you to screen at scale, debug faster, and deliver a unflawed exploiter experience across platforms.

Frequently Asked Questions (FAQs)

1. What is the dispute between implicit and denotative assertions in Cypress?

Implicit assertions use Cypress commands like .should() and .and()that automatically retry until the status is met. Explicit assertions use JavaScript statement library likeexpect() or assert() for more controlled, one-time evaluations.

2. Can I use both should () and anticipate () in the same Cypress tryout?

Yes, you can unite both. Use.should() for built-in, retryable cheque, andexpect()for complex weather or values obtained via.then() recall.

3. What libraries power Cypress asseveration?

Cypress statement are powered byChai, Chai-jQuery, and Sinon-Chai, countenance a mix of BDD, TDD, and DOM-specific assertions.

4. How do I debug failed assertions in Cypress tests?

Cypress provides detailed error messages, DOM snapshots, and test runner logs for failed assertions. Integrating with tools like gives you screenshots, video transcription, and console logs for yet deeper debugging on existent devices.

Tags
66,000+ Views

# Ask-and-Contributeabout this topic with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free