Suppose I want to add a log at the beginning of each command and at the end of each command. I want to be able to do that for all commands at once. So I tried:
// Define a function to intercept custom commands
const logCustomCommand = (originalFn) => {
return function () {
const commandName = originalFn.name;
cy.log(`Custom Command: ${commandName} - Started`);
// Execute the original custom command function
const result = originalFn.apply(this, arguments);
cy.log(`Custom Command: ${commandName} - Ended`);
return result;
};
};
// Intercept all custom commands to add logging
Cypress.Commands.overwrite('*', logCustomCommand);
But I got:
Cannot overwrite command for: *. An existing command does not exist by that name.
Can you advise please?
The obvious approach is to create a list of the command you want to apply:
const commands = ['check', 'uncheck', 'click', 'dblclick', 'rightclick'...]
commands.forEach(command => {
Cypress.Commands.overwrite(command, logCustomCommand)
})
Or if you struggle with typing command names into the editor:
Object.keys(cy.commandFns).forEach(command => {
Cypress.Commands.overwrite(command, logCustomCommand)
})
Also works for custom commands
Cypress.Commands.add('aCustomCommand', () => {
return 'I-appear-in-cy-commands'
})
const commandNames = Object.keys(cy.commandFns)
expect(commandNames).to.include('aCustomCommand')