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.

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

Top comments (0)

This post blew up on DEV in 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay