Sometimes you want to change how a built-in Cypress command works to fit your test better. Overwriting commands lets you do that easily.
0
0
Overwriting existing commands in Cypress
Introduction
You want to add extra logging every time a command runs.
You need to change the default behavior of a command for your app.
You want to add custom checks before or after a command runs.
You want to reuse a command but with some tweaks.
You want to fix or improve a command without changing all your tests.
Syntax
Cypress
Cypress.Commands.overwrite('commandName', (originalFn, ...args) => { // your custom code here return originalFn(...args) })
originalFn is the original command you are overwriting.
You must call originalFn(...args) to keep the original behavior unless you want to replace it fully.
Examples
This example adds a console log every time
cy.click() runs, then does the normal click.Cypress
Cypress.Commands.overwrite('click', (originalFn, subject, options) => { console.log('Click command is called') return originalFn(subject, options) })
This changes
cy.visit() so if you give a path, it adds the base URL automatically.Cypress
Cypress.Commands.overwrite('visit', (originalFn, url, options) => { if (!url.startsWith('http')) { url = 'https://example.com' + url } return originalFn(url, options) })
Sample Program
This test overwrites the type command to always type uppercase letters. It logs the text before typing.
Cypress
Cypress.Commands.overwrite('type', (originalFn, subject, text, options) => { console.log(`Typing text: ${text}`) return originalFn(subject, text.toUpperCase(), options) }) describe('Overwrite type command test', () => { it('types uppercase text', () => { cy.visit('https://example.cypress.io') cy.get('.search-input').type('hello') }) })
OutputSuccess
Important Notes
Always call the original function unless you want to fully replace the command.
Overwriting commands affects all tests, so use carefully.
Use descriptive console logs to help debug overwritten commands.
Summary
Overwriting commands lets you change how Cypress commands work.
You get the original command as a function to call inside your overwrite.
Use overwrites to add logging, change behavior, or fix commands.