DEV Community

David Johnston
David Johnston

Posted on

What do you think about providing Cypress and RTL selector and assertion functions alongside your components?

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. 

Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

These would contains functions like:

function selectItemInMultiSelect(label: string, itemName: string) //...

function assertMultiSelectContainsItem(label: string, itemName; string) //... 
Enter fullscreen mode Exit fullscreen mode

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?

Top comments (1)

Collapse
 
rrafatpanah profile image
Raphael Rafatpanah