Set up TypeScript in your Cypress project.

Niluka Sripali Monnankulama
Many Minds
Published in
7 min readFeb 11, 2024

--

First, let’s examine the benefits we can gain by integrating TypeScript into your Cypress project.

This integration offers several straightforward advantages:

  1. Improved Developer Experience: TypeScript offers better auto-completion and error checking in code editors like Visual Studio Code. This helps developers write code faster and with fewer mistakes.
  2. Enhanced Code Readability: TypeScript makes your code more readable and maintainable by providing clear type definitions. This makes it easier for developers to understand and work with the codebase.
  3. Reduced Errors: TypeScript’s static typing system helps catch errors early in the development process. This leads to fewer bugs and more robust test scripts.
  4. Faster Development: With TypeScript, developers can write code more quickly and confidently. The productivity gains from features like auto-completion and type checking accelerate the development cycle.

In essence, TypeScript simplifies coding, improves code quality, reduces errors, and speeds up development, making it a valuable addition to any Cypress project.

1. Setup Cypress Project

To set up Cypress in your project, follow these steps:

To set up Cypress in your project, follow these steps:

  • Install Cypress: Use npm to install Cypress as a dev dependency in your project:
npm install cypress --save-dev

This command will download and install Cypress locally, which might take a few moments.

  • Open Cypress: Once Cypress is installed, open it by running the following command:
npx cypress open

The first time you run this command, it will launch a setup wizard that guides you through the initial configuration.

  • Choose Testing Project Type: Next, you’ll be prompted to select the type of testing project you want to initialize. Choose “E2E Testing,” which is the most common scenario for end-to-end testing.
  • Initialize Project Structure: After selecting the testing project type, Cypress will initialize the necessary file structure in the root folder of your project.
├── cypress.config.js
└── cypress
├── downloads
├── e2e
├── fixtures
└── support
  • Close Setup Wizard: Once the project structure is created, you’ll be notified of the successful operation. Click the “Continue” button to proceed.
  • Browser Selection: At this point, Cypress may prompt you to select the browser you want to use for running tests. You can ignore this for now and close all open windows.

Select a Browser and Click on “Start E2E Testing in <Browser>”, then you will navigate to another wizard

In this example, we are going to choose “Chrome,” but any other browser will do. Click “Start E2E Testing in Chrome.”

Here also, either you can select their example specs or you can create a new spec..

Congratulations! You’ve successfully set up Cypress in your project. Now, you can proceed to add TypeScript for enhanced testing capabilities.

2. Configure TypeScript

To configure TypeScript for your Cypress project, follow these steps:

  • Install TypeScript: First, add TypeScript to your project’s dependencies by running the following command in your terminal:
npm install typescript --save-dev

This command will install TypeScript locally as a dev dependency in your project.

  • Initialize tsconfig.json: After installing TypeScript, you need to initialize a TypeScript configuration file called tsconfig.json. You can do this using the TypeScript compiler (tsc) with the following command:
npx tsc --init --types cypress --lib dom,es6

Here’s a breakdown of what each part of the command does:

  • npx: This utility allows you to execute commands from npm packages without having to install them globally.
  • tsc --init: This initializes a new tsconfig.json file with default settings.

And we can pass preferred compiler options.

  • --types cypress: This flag tells TypeScript to include type definitions for Cypress in the generated tsconfig.json file.
  • --lib dom,es6: This specifies to include the dom and es6 libraries, providing TypeScript with type definitions for DOM elements and ES6 features.

To help us decide on which options we need, we can take a look into the documentation

Running this command will create a tsconfig.json file in the root of your project, which serves as the TypeScript configuration file.

Additionally why we need this tsconfig.json

tsconfig.json is a configuration file used by TypeScript to control how it compiles TypeScript code into JavaScript.

It's like a set of instructions for TypeScript.

You can specify things like which version of JavaScript to target, where to output the compiled JavaScript files, which files to include or exclude, and other settings. It helps TypeScript understand how you want your code to be compiled and behave.

Important:

Rename JavaScript files to TypeScript files:

Change the extension of your JavaScript source files to .ts.

Change the extension of your Cypress test spec files from .js to .ts.

  • Example: spec.cy.js into spec.cy.ts.

Update Cypress configuration file:

Change the extension of the cypress.config.js file to cypress.config.ts and change the existing code

import { defineConfig } from "cypress";

export default defineConfig({
e2e: {
setupNodeEvents(on, config) {
// implement node event listeners here
},
},
});

Update the support/commands.js file with a commands.ts file

Update the support/index.js file with an index.ts file

Add Custom Command IntelliSense -

To enable IntelliSense for custom commands in Cypress, you can create a declaration file named index.d.ts in the cypress/support folder. Here's how you can do it:

  1. Create index.d.ts File: In your Cypress project, navigate to the cypress/support folder and create a new file named index.d.ts.
  2. Declare Custom Command Interface: In the index.d.ts file, declare an interface representing your custom commands. Each command should be declared within the Chainable interface provided by Cypress.
// cypress/support/index.d.ts  
declare namespace Cypress {
interface Chainable {
// Define the structure of your custom commands here
customCommandName(arg1: ArgType1, arg2: ArgType2): Chainable<Element>;
// Add more custom commands as needed
}
}
  • Replace customCommandName(arg1: ArgType1, arg2: ArgType2): Chainable<Element>; with the actual signature of your custom command. This declaration ensures that TypeScript recognizes the existence of these commands and provides IntelliSense support when you use them in your Cypress tests.

3. Include Declaration File: In your tsconfig.json file, ensure that TypeScript includes the index.d.ts file for type checking. You can do this by adding the following line to the include array:

{
"compilerOptions": {
// Other compiler options...
},
"include": [
"cypress/support/index.d.ts",
// Other included files or folders...
]
}

4. Usage: After adding the declaration file, you can use your custom commands in Cypress tests with full IntelliSense support. For example:

// cypress/integration/example_spec.ts  
describe('Example Test Suite', () => {
it('should demonstrate usage of custom command', () => {
// You will now get IntelliSense support for your custom command
cy.customCommandName(arg1, arg2).should('have.length', 10);
});
});
  • Refer to the “Types for Custom Commands” chapter in the official documentation for detailed examples and guidelines on creating custom commands. (”Types for Custom Commands”)

Custom Assertions:

  • Custom assertions are defined using the Chai language, which is the assertion library Cypress is built upon.
  • Extend the TypeScript assertion types to make the compiler understand the new assertion methods.
  • By defining custom assertions, you can tailor your tests to check for specific conditions or behaviors that are critical for your application.
  • Explore the documentation for comprehensive information on creating and using custom assertions effectively.

( https://github.com/cypress-io/cypress-example-recipes/tree/master/examples/extending-cypress__chai-assertions)

With these steps, you’ve added IntelliSense support for your custom commands in Cypress, making it easier to write and maintain Cypress tests with TypeScript.

To validate that the changes have been successfully implemented, follow these steps:

  1. Open Cypress:
  • Navigate to your project directory in the terminal.
  • Run the command npx cypress open to open Cypress.

2. Select Test File:

  • In the Cypress window, select the test file you want to run. Since you’ve changed the extension from .js to .ts, make sure to select the updated TypeScript file.

3. Run a test in the selected browser:

  • Choose your preferred browser to run the test.
  • Click on the test file you want to execute.

4. Verify Test Execution:

  • Once the test is executed, verify that it runs successfully without any errors.
  • Ensure that the test performs the expected actions and assertions as defined in your TypeScript test file.

By following these steps, you can confirm that your Cypress tests are still working as expected after migrating from JavaScript to TypeScript.

Indeed, when we open the TypeScript file in our browser using Cypress, the framework runs a compiler in the background to facilitate this process.

Here’s how it works:

  1. Conversion from TypeScript to JavaScript:
  • Cypress reads the .ts file containing our test script.
  • It then converts this TypeScript code into JavaScript, which is executable by the browser.

2. Injection into the Browser:

  • After the conversion, Cypress injects the compiled JavaScript code into the browser environment where the test is executed.
  • This injected code contains the necessary handlers and functions to run our test.

3. Execution in the Browser:

  • Once injected, the browser executes the test code as part of the web page.
  • The test interacts with the application under test and performs the defined actions and assertions.

4. Viewing Compiled Test File:

  • By inspecting the network panel in the browser’s developer tools and searching for the compiled .ts file (e.g., spec.cy.ts), we can see the converted JavaScript code.
  • This compiled code includes the test logic and any additional functionality generated during the conversion process.

By observing the compiled test file in the network panel, we can gain insight into how Cypress handles TypeScript files, converts them to JavaScript, and executes them within the browser environment. This process enables us to develop and run tests using TypeScript while leveraging Cypress’s testing capabilities.

Thank you for reading! I hope you found this article useful!

--

--

Niluka Sripali Monnankulama
Many Minds

An IT professional with over 7+ years of experience. Member of the WSO2 Identity & Access Management Team.