Smith Ranjan
Smith Ranjan

Reputation: 147

How can i use soft assertion in Cypress

I have configured soft-assert from npm. I ran npm i soft-assert, and now my package.json has "soft-assert": "^0.2.3"

I want to use function of softAssert() function:

softAssert(actual, expected, msg, ignoreKeys)

but don't know what the exact steps are to use it.

Example: When I use soft assertion function in my code, getting following error.

If I use it like this

cy.softAssert(10, 12, "expected actual mismatch and will execute next line") it gives me a "not supported" error.

If I use it like this

softAssert(10, 12, "expected actual mismatch and will execute next line") it gives me a "softAssert not defined" error.

Can any one tell me how to use the softAssert function in Cypress code with some small example?


Now the problem I am facing

it("asserts and logs and fails", () => {
  Cypress.softAssert(10, 12, "expected actual mismatch...");
  cy.log("text");
  Cypress.softAssertAll();
});

I need my code after soft assertion as cy.log("text") to be executed in the same it block but the current test is failing the whole it block, without executing cy.log("text") statement.

Upvotes: 13

Views: 8954

Answers (1)

Richard Matsen
Richard Matsen

Reputation: 23533

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();
})

Upvotes: 30

Related Questions