Soft assert or something similar in Cypress

Viewed 551

At the end of my test, I'm verifying multiple values to see if they're correctly captured in the form. I'm using expect statements. I realized if one expect fails, rest will not execute. All these verification are part of a single test case. I do want my test case to be marked as fail even if one expect fails but would like all the expect statements to be executed. So I can't really separate them. Is there an alternative? Do soft assertions work for Cypress?

verifyRoledetails(testobject) {

    cy.contains('h3','Role details').nextUntil('button').should(($roledetails)=> {

    expect($roledetails.children('label').get(0).innerText).to.eq('Role title');
    expect($roledetails.children('p').get(0).innerText).to.eq(testobject.role_details.title);

    expect($roledetails.children('label').get(1).innerText).to.eq('Where is the role based');
    expect($roledetails.children('p').get(1).innerText).to.eq(testobject.role_details.role_basedat);

 })
};
1 Answers

Please see this answer, which gives a straight-forward way using package soft-assert

const jsonAssertion = require("soft-assert")

verifyRoledetails(testobject) {

  cy.contains('h3','Role details').nextUntil('button')
    .should(($roledetails)=> {

      const label1Text = $roledetails.children('label').get(0).innerText;
      jsonAssertion.softAssert(label1Text, 'Role title');

      const p1Text = $roledetails.children('p').get(0).innerText;
      jsonAssertion.softAssert(p1Text, testobject.role_details.title);

      const label2Text = $roledetails.children('label').get(1).innerText;
      jsonAssertion.softAssert(label2Text, 'Where is the role based');

      const p2Text = $roledetails.children('p').get(1).innerText;
      jsonAssertion.softAssert(p2Text, testobject.role_details.role_basedat);

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

But that's a bit of a flip-flop in terms of format.

To stick with the expect().matcher() pattern, try @alfonso-presa/soft-assert

const { proxy, flush } = require("@alfonso-presa/soft-assert");
const { expect } = require("chai");
const softExpect = proxy(expect);

verifyRoledetails(testobject) {

  cy.contains('h3','Role details').nextUntil('button')
    .should(($roledetails)=> {

      const label1Text = $roledetails.children('label').get(0).innerText;
      softExpect(label1Text).to.eq('Role title');

      const p1Text = $roledetails.children('p').get(0).innerText;
      softExpect(p1Text).to.eq(testobject.role_details.title);

      const label2Text = $roledetails.children('label').get(1).innerText;
      softExpect(label2Text).to.eq('Where is the role based');

      const p2Text = $roledetails.children('p').get(1).innerText;
      softExpect(p2Text).to.eq(testobject.role_details.role_basedat);

      flush()   // Now fail the test if above fails
    })
})
Related