Cypress Test Snippets for React Applications

Adam Drake
4 min readSep 28, 2023

--

I work on many React applications and I like to have realistic tests for these apps. I am a fan of Cypress for End-to-End testing and I think its a great tool to use to give yourself a certain level of confidence in the UI features you are building. It by no means covers everything but it does cover enough to make it worthwhile in your codebase.

I also believe in removing as much ‘friction’ as possible from your day to day workflow. The smoother a process is, the more likely you are to do it. There are a few ‘friction’ moments I have when creating tests for cypress and hence the need for this article.

I also believe in removing as much ‘friction’ as possible from your day to day workflow because the smoother a process is, the more likely you are to do it.

My most common problem is remembering the specific syntax for testing certain UI feature such as working in tables, select fields, input fields, menus, toggles etc. In this article I will share a few snippets that can be useful in these situations. (I may well write a VScode Extension at some point with these snippets but let’s see if I ever get to that. If so I will update this article with the link).

Cypress Snippets

Below you will find a variety of snippets for less usual cypress commands that are a bit more specific than the usual cypress commands.

New Cypress Commands

These pieces of code are added to the cypress/support/commands.ts file.

Cypress.Commands.add('getBySel', (selector, ...args) => {
return cy.get(`[data-test=${selector}]`, ...args);
});

This command allows you to add an attribute to React JSX Components of data-test and then target them from your cypress tests. Very useful for targeting difficult to get at elements.

Cypress.Commands.add('upload', (file: string) => {
cy.getBySel('upload-btn').click({ force: true });

const filePath = `cypress/fixtures/${file}.json`;
cy.get('input[type="file"]').eq(0).selectFile(filePath, { force: true });
});

This command allows you to upload a specific file from the cypress/fixtures folder into your test.

// Custom comand to handle uploading a file using react-dropzone
Cypress.Commands.add(
'upload',
{
// @ts-ignore
prevSubject: 'element',
},
(subject, file, fileName) => {
// we need access window to create a file below
cy.window().then((window) => {
// line below could maybe be refactored to make use of Cypress.Blob.base64StringToBlob, instead of this custom function.
// inspired by @andygock, please refer to https://github.com/cypress-io/cypress/issues/170#issuecomment-389837191
const blob = b64toBlob(file, '', 512);
// Please note that we need to create a file using window.File,
// cypress overwrites File and this is not compatible with our change handlers in React Code
const testFile = new window.File([blob], fileName);
cy.wrap(subject).trigger('drop', {
dataTransfer: { files: [testFile], types: ['Files'] },
});
});
}
);

This command allows you to upload a specific file via the react-dropzone interface.

Testing Tables

cy.getBySel('table') // See above
.get('tbody > tr')
.eq(0) // Pick first row in table. Change number to target different rows
.getBySel('picker-btn')
.click();

The above allows you to target a specific tr in a table (assuming you have the data-test attribute on the table. Useful for testing correct data is showing in the correct place on a table.

Form Fields

cy.get('input[name="name"]').type('test run name').should('have.value', 'test run name');

Targeting an input field with a specific name and then typing in it.

Select Fields (Mantine only… Sorry!!)

cy.getBySel('select-field').click();
cy.get('.mantine-Select-itemsWrapper').eq(0).click();
cy.contains('filter').should('be.visible');

This targets a specific select field, opens the options and then selects and option based on the number in the eq() command.

Conclusion

By creating snippets for those ‘harder-to-remember’ parts of the cypress syntax, it is more likely I will write more tests and hence have a higher level of confidence in the quality of the apps I am working on. Snippets are a low effort method of improving a process. Please let me know if you have any useful Cypress snippets and I can add them to this article for other develops to learn and benefit from.

About me

I am a Frontend Developer working mainly with React and Typescript in my day to day professional life. I love exploring new tools and libraries and love the Javascript Ecosystem.

I like to write blog posts that share exciting new tools I’ve discovered, how-to articles and also the occasional opinion post.

I live in Prague in the Czech Republic with my family.

Check out the original blog post on my blog here.

--

--

Adam Drake

I'm a Frontend Developer and I write about all things Frontend Related - Think lightly of yourself and deeply of the world. Based in Prague, CZ