📜  Cypress.currentTest - Javascript (1)

📅  最后修改于: 2023-12-03 15:30:14.237000             🧑  作者: Mango

Cypress.currentTest - Javascript

Cypress.currentTest is a global object provided by Cypress that represents the currently running test - it is accessible from within any test function.

Usage

To access Cypress.currentTest in your test, simply reference it:

it('should test something', () => {
  // reference Cypress.currentTest
  const currentTest = Cypress.currentTest

  // use currentTest to gather information about the test
  console.log(currentTest.title) // outputs "should test something"
})

You can use Cypress.currentTest to gather information about the test:

// get the full test title
const title = Cypress.currentTest.title

// get the current test state (passed, failed, skipped)
const state = Cypress.currentTest.state

// get the parent suite's title
const suiteTitle = Cypress.currentTest.parent.title

// get the parent suite's full title
const suiteFullTitle = Cypress.currentTest.parent.fullTitle()

// get the parent suite's duration
const suiteDuration = Cypress.currentTest.parent.duration

// get the number of retries attempted for this test
const retries = Cypress.currentTest.currentRetry()

// get the number of tests that are part of this suite
const totalTestsInSuite = Cypress.currentTest.parent.tests.length
Example

Here is an example of how to use Cypress.currentTest to log additional information when a test fails:

it('should test something', () => {
  // reference Cypress.currentTest
  const currentTest = Cypress.currentTest

  // test some functionality
  const x = 2 + 2

  // expected value
  const expected = 5

  // check if the result is correct
  if (x !== expected) {
    // log additional information when the test fails
    const message = `expected ${x} to be ${expected}`
    console.log(currentTest.title + ' failed: ' + message)
    cy.wrap(true).should('be.false', message)
  } else {
    cy.wrap(true).should('be.true')
  }
})
Conclusion

Cypress.currentTest is a useful object provided by Cypress that allows you to gather information about the currently running test. You can use it to log additional information when a test fails, or to gather statistics about the tests that are being run.