0

I try to enter into the catch statement when the 'focus()' command fails but without a result. Here is my custom command code:

Cypress.Commands.add('element', (selector: string) => {
try {
        cy
            .get(selector)
            .focus()
            .should('not.be.disabled')
} catch (error) {
    cy.log('element', __filename.split(__dirname + "/").pop(), error);
};
});

Here is my test class code:

describe("'elementNoFocus' custom command example.", () => {
    it("example shows how to use 'elementNoFocus' custom command example.", () => {
        cy.visit('https://demoqa.com/buttons');
        cy.xpath('(//*[contains(text(),"Click Me")])[3]').click();
        cy.get('#dynamicClickMessage');
    });
});

In result my code doesn't fall in to the catch statement.

enter image description here

Zoe
  • 27,060
  • 21
  • 118
  • 148
Ivan Markov
  • 129
  • 4
  • 15

1 Answers1

1

The answer of why your catch clause does not catch the error is simple: asynchronous execution.

When JS executes your command, Cypress just enqueues get, focus and should cy commands and the function returns without any UI actions performed. So it can't throw any error at this moment. They will executed lately and it's impossible to catch that real error by a catch clause

Mikhail Bolotov
  • 976
  • 1
  • 6
  • 13