Cypress has a lot of built-in commands. You can add your own custom commands. If there are a lot of custom commands, it might be useful to group them by namespace. Here is one hack I found to do so:
1 | // instead of "flat" cy.add commands |
Let's do this.
TypeScript project
First, let's create a simple Cypress project. We will use TypeScript to make sure our namespaces and commands agree. We can use index.d.ts
file to add the new custom command type definition to the cy
object.
1 | // the support file has the custom command implementation |
1 | // the index.d.ts file has the "cy.add" definition |
We can use the custom command cy.add
from our spec
1 | it('uses the custom command add', () => { |
🎁 You can find the source code for this blog post in the public repo bahmutov/cypress-namespaces. The "normal" code above is located in the branch normal.
Namespace object
Let's copy our custom command into a namespace object called "math". We need to place the method in cy.math
and we need to update the types.
1 | Cypress.Commands.add('add', (a: number, b: number) => { |
Simple, right? We simply create an object cy.math
and put references to the custom commands we want to be there. Let's update the types
1 | declare namespace Cypress { |
Instead of removing the cy.add
completely, I use @deprecated
JSDoc tag.
In our tests we can safely use cy.math.add
1 | it('uses the custom namespace', () => { |
Works like a charm.