Cypress Env Types

Give proper types to the values returned by the "Cypress.env" calls.

Let's say you store the user login information used during tests in your Cypress config object.

cypress.config.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const { defineConfig } = require('cypress')

module.exports = defineConfig({
e2e: {
env: {
users: {
standard: {
username: 'standard_user',
password: 'secret_sauce',
},
...
},
},
},
})

A spec can grab the user login information and log in

cypress/e2e/logs-in.cy.ts
1
2
3
4
5
6
import { LoginPage } from '@support/pages/login.page'

it('logs in', () => {
const user = Cypress.env('users').standard
LoginPage.login(user.username, user.password)
})

What is the type of the user value? We get it from the Cypress.env('users') object, which is ... "any". This propagates to the fields user.username and user.password

The user object and its properties have type "any"

Note: I am using the any-xray VSCode plugin to highlight all any TS values at all times.

any-xray plugin homepage

Let's fix the Cypress.env('users') type following this StackOverflow advice. We can add Cypress.env method definition to the ambient types file cypress/support/index.d.ts:

cypress/support/index.d.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/// <reference types="cypress" />
declare namespace Cypress {
type LoginInfo = import('../e2e').LoginInfo

interface Chainable {
// custom "cy" commands
}

interface Cypress {
/**
* Returns an object with configured users. Values are set
* using in the `cypress.config.js` or environment variables.
* @see https://on.cypress.io/configuration
*/
env(key: 'users'): {
/**
* The "normal" user login information
*/
standard: LoginInfo
lockedOut: LoginInfo
problem: LoginInfo
glitch: LoginInfo
}
}
}

Tip: I am using inline type LoginInfo = import('../e2e').LoginInfo to avoid using import or /// <reference path=... which would change the cypress/support/index.d.ts to a "normal" TS module. I want to preserve cypress/support/index.d.ts as an ambient definition file, see this StackOverflow discussion

Let's take a look at the spec file again.

All values have the correct types

No more any values in our Cypress spec.

🎓 This blog post is based on a lesson in my Testing The Swag Store online course.