cypresscypress-custom-commands

How to log the previous subject in custom commands in Cypress


I want to add logs to my custom commands in Cypress, for example

Cypress.Commands.add('shouldBeVisible',
    {
        prevSubject: 'element',
    },
    (subject) => {
        var getText = cy.wrap(subject);
        // cy.wrap(subject).invoke('val').then((element) =>{
        //     cy.log('element:: ' + cy.wrap(subject).get(subject))
        // });

        const log = Cypress.log({
            name: "shouldBeVisible",
            displayName: "SHOULD BE VISIBLE",
            message: [
              `👁️ (element: `+subject+` should be visible)`,
            ],
            // @ts-ignore
            autoEnd: false,
            consoleProps() {
              return subject
            },
          })

        cy.wrap(subject).should('be.visible');
    }
)

when I call it like this:

  cy.visit('https://docs.cypress.io/guides/overview/why-cypress');
  cy.get('.headerWrapper_tu51').shouldBeVisible();

I want it to log the calling function or calling element:

enter image description here


Solution

  • It's expecting a pure string for the message property, but subject is a jQuery object and it does not stringify elegantly.

    Cypress internally uses Cypress.utils.stringifyActual() which you can also use in custom commands, to convert the jQuery object into a log-friendly string.

    This test illustrates the usage,

    cy.visit('https://docs.cypress.io/examples/applications');
    
    cy.get('h2').eq(0)
      .then(subject => {
        expect(Cypress.utils.stringifyActual(subject))
          .to.eq('<h2#Kitchen-Sink.anchor.anchorWithStickyNavbar_LWe7>')
      })
    

    so in your log call

    const log = Cypress.log({
      name: "shouldBeVisible",
      displayName: "SHOULD BE VISIBLE",
      message: `👁️ (element: ${Cypress.utils.stringifyActual(subject)} should be visible)`,
      ...