Adding Cypress Custom Commands with Typescript: Check Downloaded Files

Jaime Torres
Version 1
Published in
2 min readJul 7, 2022

Cypress and Typescript

Cypress ships with official type declarations for TypeScript. This allows you to write your tests in TypeScript. This is very useful since Typescript uses strong typing which helps us detect errors at compile time but also means that we always need to have the types we are going to use defined.

Cypress custom commands

Cypress comes with its own API for creating custom commands and overwriting existing commands which allow us to encapsulate functionality so we don’t have to repeat code and make our tests more readable.

Check downloaded file command

As an example, let’s imagine that we have already defined several tests and in all of them we want to check a file that is downloaded and it's content. Instead of having to add the same code in all the tests, we can create a command that makes our work easier.

The first step is to create a function that contains all the logic of our command. Our commands should be in cypress/support/ so we are going to use the existing file commands.ts to add our command:

In this file we are going to create our function checkDownloadedFile (lines 13–20) that receive the name of the file and build the file path using the default cypress folder:

Then we are going to use the readFile function from cypress to open the file and if it exists, check the content:

Finally, you can add the checkDownloadedFile command to the global Cypress Chainable interface:

As a final step, we need to add the new command to cypress to be able to use it with the cy object. We need to use index.ts in cypress/support/ to add our new command:

And that's all! Now we can use it in any test:

Chainable command

As you have seen, the previous command was of type void, but what if we need it to be chainable? There is no problem!

Following the same approach of the previous section, we only need to add the new command function but in this case, we return the cy object using all that we need to find, in this case, a button that contains ‘Download’:

Just like before, we must add our new command in cypress/support/index.ts :

So now we can use it in our tests:

Official Cypress documentation: Cypress and Typescript

About the Author:
Jaime Torres is a Senior Software Engineer in Version 1’s NIDCS Practice.

--

--

Jaime Torres
Version 1

Kotlin and Java Principal Software Engineer @Version1, T-Shape Engineer