Is there a way to configure unique commands for Cypress using TypeScript?

Embarking on a new project, I added TypeScript and cypress as dependencies to my yarn setup. To kick things off, I crafted an example test with a custom command nestled within it. This particular test can be found in the file

cypress/e2e/cypress/example.cy.ts
, flowing like so:

describe('Example', () => {
        it('example', () => {
                cy.myCommand();
        })
})

The custom command script resides snugly in

cypress/e2e/cypress/support/commands.ts
. Its contents are as follows:

Cypress.Commands.add('myCommand', () => {
        cy.visit('https://example.cypress.io')
})

A snag I encountered is when running this setup in Cypress, my test hits a wall with the error message: "cy.myCommand is not a function". How can I fine-tune my tests for optimum performance?

For reference, my Cypress version is 13.6.5.

Answer №1

After adding cypress and TypeScript as dependencies, it's important to ensure proper configuration for them to work correctly. By combining insights from various sources, I discovered the following solution:

  • To start, rename

    cypress/e2e/cypress/support/e2e.js
    to
    cypress/e2e/cypress/support/e2e.ts
    . This file simply imports commands.{js|ts}.

  • Next, update commands.ts with the following code snippet:

    declare namespace Cypress {
        interface Chainable<Subject = any> {
            myCommand(): Chainable<any>;
        }
    }
    
    Cypress.Commands.add('myCommand', () => {
        cy.visit('https://example.cypress.io')
    })
    
  • Rename cypress.config.js to cypress.config.ts (located in the root directory of your project).

  • Add this line to cypress.config.ts:

    supportFile: 'cypress/e2e/cypress/support/e2e.ts'
    

As an additional note on May 31 2024: If you are using yarn as your package manager, consider creating a .yarnrc.yml file with the following contents:

nodeLinker: node-modules

yarnPath: .yarn/releases/yarn-4.1.1.cjs

This adjustment instructs yarn to create the node_modules directory at the root of your yarn project to facilitate VSCode finding necessary types for syntax checking.

These steps were taken based on insights from: Typescript cannot find type in definition file in node_modules folder

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Interactive Checkbox Grouping based on Labels

I am working with an Array example: Data: Array<any> = [ { name: 'Pear', value: 'pear' ,label : Fruit}, { name: 'Plum', value: 'plum' , label : Fruit}, { name: 'Kiwi', value: 'kiwi&a ...

NeedValidation.required, Validation.emailCheck

When creating a form in TypeScript, I encountered an issue: private _createForm() { this.addForm = this._formBuilder.group({ login: [ null, Validators.required ], name: [ null, Validators.required ], surname: [ null, Validators ...

Oops! Looks like there was an issue with parsing the module. It seems there is an unexpected character '@' in the file. Make sure you have the proper loader configured to handle this file type

Angular version: 14.2.7 I added a unique CSS library to my Angular project that is not publicly available. After adding it to app.module.ts: import { SapphireButtonModule } from '@sapphire-angular/core'; imports: [ SapphireButtonModule, ...

Navigating Between Pages with Parameters in Ionic 2 (starter app)

I have an Ionic 2 project with a blank template containing a page that displays a list. Upon clicking on an item in the list, the user should be able to view more details about that specific item. Below are the files related to the list: list.html: <i ...

What does the generic argument on the right side of the statement indicate in TypeScript?

Can you identify the name of <R> in TypeScript? It appears to be a type that is derived from the passed argument, with no clear documentation available. The generic portion only delves into the details of the left side <S>. type F< ...

Ensuring the accurate usage of key-value pairs in a returned object through type-checking

After generating a type definition for possible response bodies, I am looking to create a function that returns objects shaped as { code, body }, which are validated against the typing provided. My current solution looks like this: type Codes<Bodies> ...

What is the best way to initiate a class constructor with certain parameters left out?

Currently, I am facing a challenge while trying to pass various combinations of arguments to a class constructor. The constructor has 2 optional arguments. Here is the code snippet: class MyClass { foo(a, b) { return new MyClass(a, b); } bar( ...

Extraction of properties from an object in an ES6 class

How should object destructuring be properly applied for methods within ES6 classes? user.ts import { Request, Response } from "express"; export class User { constructor (){ Object.assign(this,{ root:this.root, get:this.get ...

Adjust the key values within an array of objects in TypeScript

I am looking to update the keys' values of the 1st object within an array of objects. Here is what I have attempted so far: The array of objects: const objArray: FoodItems[] = [ { apple: 4, banana: 7, 'mango & grapes': ...

Having trouble importing a TypeScript module from the global node_modules directory

I have a library folder located in the global node modules directory with a file named index.ts inside the library/src folder //inside index.ts export * from './components/button.component'; Now I am trying to import this into my angular-cli ap ...

Utilizing Angular's Dependency Injection to Provide Services to External Libraries

I'm currently developing an NPM package that enhances the functionalities of Material Datatable. One standout feature is the ability to specify a method that will be triggered when a user clicks on a specific cell. Here is how the property is defined ...

Leveraging characteristics of combined types

Can anyone help me understand how to work with union and generic types by re-implementing something similar to Either or Option? Here is the code I have: type Error = { readonly _tag: 'error'; status: number; statusText: string; }; type Su ...

In Deno, it is possible to confirm that a variable is an instance of a String

I'm having trouble asserting instances of string in Deno: import { assertInstanceOf } from "https://deno.land/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2642405050405e445e59445e">[email protected]</a& ...

Issue with Dates in Typescript array elements

When attempting to compare different Date elements in my code, I encountered an issue. I have two date elements representing date formats but am unable to compare them because I keep receiving the error message "core.js:6237 ERROR TypeError: newticketList. ...

Guide to activating data transfer object validators in NEST JS

I have recently started using NEST JS and I am currently working on implementing validators in DTO's. This is what my code looks like: // /blog-backend/src/blog/dto/create-post.dto.ts import { IsEmail, IsNotEmpty, IsDefined } from 'class-validat ...

Encountering a TypeError while working with Next.js 14 and MongoDB: The error "res.status is not a function"

Currently working on a Next.js project that involves MongoDB integration. I am using the app router to test API calls with the code below, and surprisingly, I am receiving a response from the database. import { NextApiRequest, NextApiResponse, NextApiHandl ...

Bringing together the functionality of tap to dismiss keyboard, keyboard avoiding view, and a submit button

On my screen, there's a big image along with a text input and a button at the bottom. The screen has three main requirements: When the user taps on the input, both the input and button should be visible above the keyboard The user must be able to ta ...

Obtain every selection from the multiselect box and add them to the database

How do I assign all selected measures to my "answers" object? The selected measures are: get selectedMeasures() { const items = this.measureItems.filter((item: any) => item.selected); return items.length ? JSON.stringify(items.map(item => ...

What methods can be used to reach an interface within a namespace that is not deemed for export?

The type definition for Traverson is structured in the following way: declare var traverson: Traverson.TraversonMethods; export = traverson; declare namespace Traverson { interface TraversonMethods { from(uri: string): Builder; } i ...

Typescript struggling to comprehend the conditional rendering flow

I am facing an issue with the code snippet below: import * as React from 'react' type ComponentConfig = [true, {name: string}] | [false, null] const useComponent = (check: boolean): ComponentConfig => { if (check) { return [true, {name ...