DEV Community

Cover image for On proactively naming elements within Cypress '.within()' blocks
Sam E. Lawrence
Sam E. Lawrence

Posted on

On proactively naming elements within Cypress '.within()' blocks

Anytime you use .within() in a Cypress test, you have the option to name the element variable that you pass into the function body. Here's an example where the element scope is named:

cy.get('#el').within(('optionallyNamedElement') => {
  cy.log('foo');
});
Enter fullscreen mode Exit fullscreen mode

but here's another perfectly functional example where it isn't:

cy.get('#el').within(() => {
  cy.log('foo');
});
Enter fullscreen mode Exit fullscreen mode

If the named element term isn't used in the function body, should we assign it a name when we write this test code? I think we should.

It's ok if someone comes along later and changes this name, but I think it's a courtesy to future programmers to give them a semantic name here for future use. This name might use a consistent style across the test codebase, or just provide a way for a future programmer to avoid getting stuck in future by having to pause to come up with a name. Remember, that future programmer might be you!

I also think that proactively providing a name here makes code more clear, approachable, and debuggable. By naming the element, when a bug arises, you at least have a clue of what element you thought you were scoped within.

When I use .within() these days, I always try to remember to name the scope that I'm entering, even when that variable never gets used in the function body.

Top comments (0)