Cypress: How to log each element click to a file?

54 Views Asked by At

I created a log file in which I log there various operations during my tests. I would also like to log any elements click I perform. However, I don't want to add a specific log instruction before each click command, but I want it to log the click seamlessly.

I tried to overwrite the click command like this:

Cypress.Commands.overwrite(
 'click',
 (originalFn, subject, positionOrX, y, options = {}) => {
    Logger.log('I just clicked ' + subject)
    return originalFn(subject, positionOrX, y, options);
 }
);

but somehow it broke my tests.

For example, I have this login command which is the first I use in the before hook:

Cypress.Commands.add('loginSys', (username = Cypress.env("USERNAME"), password = Cypress.env("PASSWORD")) => {

    cy.clearAllLocalStorage()

    cy.intercept('POST', '*login*').as('login')
    cy.visit(getCMUrl())
    cy.login(username, password)
    cy.wait('@login').then((interception) => {
        const token = interception.response.body.token
        Cypress.env('ACCESS_CODE', token)
    })
})

I receive the following error:

Cypress detected that you returned a promise from a command while also invoking one or more cy commands in that promise.

The command that returned the promise was:

> cy.type()

The cy command you invoked inside the promise was:

> cy.log()

Because Cypress commands are already promise-like, you don't need to wrap them or return your own promise.

This error happens as I overwrite click command.

1

There are 1 best solutions below

2
Mezi Atwood On

The .login() command will have a .type() command in it (possibly two, user & password).

Cypress says this about .type()

If the element is currently not in focus, before issuing any keystrokes Cypress will first issue a .click() to the element to bring it into focus.

Probably explains the link between your .click() overwrite and the "broken" cy.login().

So, when logging in the overwrite don't use cy.log() use the alternate Cypress.log() instead.

Useful when writing your own custom commands.