How can i use soft assertion in Cypress

The soft assertion concept is pretty cool, and you can add it with minimal implementation to Cypress

const jsonAssertion = require("soft-assert")

it('asserts several times and only fails at the end', () => {
  jsonAssertion.softAssert(10, 12, "expected actual mismatch");
  // some more assertions, not causing a failure

  jsonAssertion.softAssertAll();  // Now fail the test if above fails
})

To me, it would be nicer to see each soft assertion failure in the log, so it’s possible to add custom commands to wrap the soft-assert functions

const jsonAssertion = require("soft-assert")

Cypress.Commands.add('softAssert', (actual, expected, message) => {
  jsonAssertion.softAssert(actual, expected, message)
  if (jsonAssertion.jsonDiffArray.length) {
    jsonAssertion.jsonDiffArray.forEach(diff => {

      const log = Cypress.log({
        name: 'Soft assertion error',
        displayName: 'softAssert',
        message: diff.error.message
      })
    
    })
  }
});
Cypress.Commands.add('softAssertAll', () => jsonAssertion.softAssertAll())


//-- all above can go into /cypress/support/index.js
//-- to save adding it to every test (runs once each test session)



it('asserts and logs but does not fail', () => {
  cy.softAssert(10, 12, "expected actual mismatch...");
  cy.log('text');    // this will run
})

it('asserts and logs and fails', () => {
  cy.softAssert(10, 12, "expected actual mismatch...");
  cy.log('text');    // this will run

  cy.softAssertAll();
})

Leave a Comment