What do you think about providing Cypress and RTL selector and assertion functions alongside your components?
David Johnston
Posted on September 6, 2022
Here's an idea I've just started toying with.
So in my project the folder structure for any given component looks like this:
/MyComponent
MyComponent.tsx - The actual component
MyComponent.stories.tsx - Storybook stories
MyComponent.test.tsx - RTL tests.
Fairly straight forward.
Something I've been running into recently, particularly with writing Cypress tests, is that often writing either interactions with my components (eg. click the button, select an item from the autocomplete) or assertions on them (eg. the multiselect contains value 'foo') has quite a lot friction. I'm often going into the RTL test and seeing what I've done there, and copying an modifying it.
Now I know that Testing Libraries whole philosophy is 'write tests in the way that a user would interact with the application' - but it's often not that straightforward, or it's a bit tedious.
So what I've considered is two more files along side the others;
MyComponent.rtl-selectors.ts
MyComponent.cypress-selectors.ts
These would contains functions like:
function selectItemInMultiSelect(label: string, itemName: string) //...
function assertMultiSelectContainsItem(label: string, itemName; string) //...
And the idea is, you could import these functions in your RTL/Cypress tests to assist with interactions.
Has anyone tried such a thing, and how did it go?
Posted on September 6, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.