In Cypress, soft assertions refer to the ability to continue executing automated tests even if certain assertions fail, without immediately interrupting the test flow. Cypress itself does not natively support soft assertions, but you can achieve this functionality by integrating third-party libraries.
A popular solution is to use the chai-soft-assert plugin, which can be used alongside Cypress to support soft assertions. Below is an example of how to use soft assertions in Cypress:
-
Install the required libraries First, you need to install
chaiandchai-soft-assert. You can do this by running the following npm command:shellnpm install chai chai-soft-assert --save-dev -
Configure Cypress to support soft assertions Next, in your Cypress support file (typically
cypress/support/index.js), you need to import and use these two libraries:javascriptimport chai from 'chai'; import softAssert from 'chai-soft-assert'; chai.use(softAssert); cy.softExpect = chai.softExpect; cy.softAssert = chai.softAssert; -
Use soft assertions in tests Now you can use
cy.softExpectorcy.softAssertto perform soft assertions in your test cases. Here is a specific test example:javascriptdescribe('Soft Assertion Example', () => { it('should allow multiple assertions even if one fails', () => { cy.visit('https://example.com'); cy.get('h1').invoke('text').then((text) => { cy.softExpect(text).to.equal('Example Domain'); cy.softExpect(text).to.contains('Example'); // Intentionally failing assertion }); cy.get('p').invoke('text').then((text) => { cy.softAssert(text).to.contains('illustrative examples'); }); cy.softAssert.assertAll(); // Ensure all soft assertions are verified }); });In the above code,
cy.softExpectandcy.softAssertallow you to perform multiple assertions within anitblock. Even if some assertions fail in the middle, the test continues to execute untilcy.softAssert.assertAll()is called, which aggregates all assertion results and reports failures if any occur.By using this approach, Cypress can implement soft assertions, enhancing test flexibility and robustness. This is particularly useful when handling complex business logic and multiple validations, as it ensures that other critical functionalities can be verified within a certain fault tolerance, rather than interrupting the test at the first error.