如何在我的 Cypress 测试中实现软断言

How can I imlement soft Assertion in my Cypress test

我正在为在我的赛普拉斯测试中实施软断言而苦苦挣扎。 我需要将所有断言转换为软断言。我遇到的问题是我无法在 jsonAssertion 中找到该元素。例如 cy.get('span[class="h4"]') 是元素,我需要断言它包含一些文本。如何使用 jsonAssertion.softAssert()?

这是我的测试:

describe('Load Validation Test', function(){
  const jsonAssertion = require("soft-assert")

  it('Load Validation Test', function(){
      let url = Cypress.config().baseUrl
      
      cy.visit(url+'activityTaskManagement')

      cy.get('span[class="h4"]').should('contain.text','Manage Activities')
      cy.get('button[ng-click="vm.addActivityTask();"]').should('be.visible')
      cy.get('button[ng-click="vm.addActivityTaskBulk();"]').should('be.visible')
      cy.get('input[placeholder="Activity Name"]').should('be.visible')
      cy.get('div table[class="table table-striped b-t b-light table-nowrap"]').should('be.visible')
      
  })
})

如果您只想断言元素 span[class="h4"] 有一些文本,您可以这样做:

cy.get('span[class="h4"]').should('include.text','Manage Activities')

使用软断言你可以做这样的事情:

const jsonAssertion = require('soft-assert')

describe('Load Validation Test', function () {
  it('Load Validation Test', function () {
    let url = Cypress.config().baseUrl
    cy.visit(url + 'activityTaskManagement')

    cy.get('span[class="h4"]')
      .invoke(text)
      .then((text) => {
        jsonAssertion.softContains(
          text,
          'Manage Activities',
          'Some custom message'
        )
      })

    cy.get('button[ng-click="vm.addActivityTask();"]').should('be.visible')
    cy.get('button[ng-click="vm.addActivityTaskBulk();"]').should('be.visible')
    cy.get('input[placeholder="Activity Name"]').should('be.visible')
    cy.get(
      'div table[class="table table-striped b-t b-light table-nowrap"]'
    ).should('be.visible')
  })
})

对于 soft-assert,参见

作为自定义命令,

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

测试中

cy.get('span[class="h4"]').then($el=> {
  const actual = $el.text()
  cy.softAssert(actual, 'Manage Activities')
})

还有代理包 expect

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

cy.get('span[class="h4"]')
  .invoke('text')
  .should(actual => {
    softExpect(actual).to.eq('Manage Activities')
  })

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