During testing, the custom command in TypeScript for Cypress is not being recognized, resulting in the error message 'TypeError: cy.a is not a function'

In my Cypress test specification, I have a simple test for the first page displayed. The code looks like this:

// integration/connection.ts

describe("First page displayed", function() {
    before(() => {
        cy.visit("/")
    })

    it("Is an error page when no token is given", function() {
        cy.getByDataAttribute("error-page")
    )}
})

There is a custom command called getByDataAttribute defined as follows:

// support/commands.ts

declare namespace Cypress {
  interface Chainable<Subject> {
    getByDataAttribute: typeof getByDataAttribute
  }
}

/**
 * Get a DOM element by targeting its data-cy attribute value
 * @param data_target data-cy attribute value to target
 */
function getByDataAttribute(data_target: string) {
  return cy.get("[data-cy=" + data_target + "]")
}

Cypress.Commands.add("getByDataAttribute", getByDataAttribute)

Everything is written in TypeScript and compiles without errors. But when running the test, Cypress throws an error:

TypeError: cy.getByDataAttribute is not a function

The custom command used to work fine until I added IntelliSense. Even after reverting back to vanilla JS, the command is still not recognized. I've tried various tweaks in the configuration but can't seem to resolve the issue. It should all be in order now, but it's still not working as expected.

Answer №1

To enable IntelliSense in JS, we include the following reference:

///<reference types="cypress"/>

Answer №2

Have you simplified your custom command example here? Does it involve any imports?

I encountered a similar issue when following an online tutorial, but my custom command required an object imported from another module. In such cases, using the global namespace declaration is necessary. It might be worth trying to see if the global namespace approach works for you.

Additionally, it seems like you have integrated your command into the Chainable<Subject> interface, which is typically used for chaining commands after selecting an element (e.g., cy.get("#something").myCommand()). Since your command is directly applied to cy, it should be included in the Chainable interface instead.

// support/commands.ts
import { someObject } from "someModule";

declare global { // < MAKE NOTE OF THIS FOR POINT 1)
  namespace Cypress {
    interface Chainable { // < PAY ATTENTION TO THIS FOR POINT 2)
      getByDataAttribute: typeof getByDataAttribute
    }
  }
}

/**
 * Retrieve a DOM element based on its data-cy attribute value
 * @param data_target - data-cy attribute value to target
 */
function getByDataAttribute(data_target: string) {
  // perform operations involving someObject here
  return cy.get("[data-cy=" + data_target + "]")
}

Cypress.Commands.add("getByDataAttribute", getByDataAttribute)

export {}; // < Ensure to include this at the end!

For more detailed explanations, refer to:

https://github.com/cypress-io/cypress/issues/1065#issuecomment-410324355

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

What steps are involved in launching an outdated Angular project?

Tasked with reviving an old Angular client in my company, I found myself grappling with outdated files and missing configurations. The lack of package.json, package-lock.json, and angular.json added to the confusion, while the presence of node modules in t ...

The pairing of Transpiller and Internet Explorer 8 is like a dynamic

In starting my new project, I am considering using BabelJS. However, there is a significant requirement that must be met: it needs to be compatible with IE8. ISSUE: Babel compiles ES6 to ES5, but the support for ES5 on IE8 is lacking. Are there any alter ...

Is it possible to use a single type predicate for multiple variables in order to achieve type inference?

Is there a way to optimize the repeated calls in this code snippet by applying a map to a type predicate so that TSC can still recognize A and B as iterables (which Sets are)? if(isSet(A) && isSet(B)) { ...

When employing GraphQL Apollo refetch with React, the update will extend to various other components as well

My current setup involves using react along with Apollo. I have implemented refetch in the ProgressBar component, which updates every 3 seconds. Interestingly, another component named MemoBox also utilizes refetch to update the screen at the same int ...

"Utilizing Postgresql with TypeORM for filtering many-to-many relationships

I have two entities that are connected with a ManyToMany relationship: // Branch entity @ManyToMany( (type) => User, (e) => e.branches ) users: User[]; // User entity @ManyToMany( (type) => Branch, (e) ...

This function has a Cyclomatic Complexity of 11, exceeding the authorized limit of 10

if ((['ALL', ''].includes(this.accountnumber.value) ? true : ele.accountnumber === this.accountnumber.value) && (['ALL', ''].includes(this.description.value) ? true : ele.description === this.description.valu ...

I am encountering an issue where the nested loop in Angular TypeScript is failing to return

I am facing an issue with my nested loop inside a function. The problem is that it is only returning the default value of false, instead of the value calculated within the loop. Can someone please point out what I might be doing incorrectly? Provided belo ...

How come my ts-mockito spy isn't delegating method calls properly?

In my code, I have a class named MyPresenter which has a method called doOperation(). This method calls another method on a View class that implements an interface and is passed in as a parameter. Below you can find the implementation of the class, interfa ...

Utilize zimJS within an Angular 4 application written in Typescript

After extensive searching, I have come up empty-handed in my quest to find the answer. There are no modules available for zimjs, only for createjs, but I require the entire package. I have exhausted all resources and still cannot find a solution. I am ke ...

Error: Uncaught Angular8 template parsing issue

I used a tutorial from this website to guide me through my project. However, upon running my angular application, I encountered the following error in the console: Uncaught Error: Template parse errors: Can't bind to 'ngModel' since it isn ...

"Enable email delivery in the background on a mobile app without relying on a server

I am currently in the process of developing a mobile app using Ionic. One feature I would like to incorporate is sending an email notification to admins whenever a post is reported within the app. However, I am facing challenges with implementing this succ ...

Using Axios and Typescript to filter an array object and return only the specified properties

I'm currently working on creating an API to retrieve the ERC20 tokens from my balance. To accomplish this, I am utilizing nextjs and axios with TypeScript. However, I'm encountering an issue where the response from my endpoint is returning exces ...

Queries with MongoDB RegEx fail to return any matches if the search string contains parentheses

When trying to implement case-insensitivity using regex, it seems to work well for plain strings. However, if special characters like parenthesis are involved in the search query for the name, the database returns no results. For example, a search for "Pu ...

Angular form retains the previous value when saving

I encountered an issue with my form component where it displays previous values instead of updated ones during a save operation. The strange part is that if I close the form and reopen it, the new values are then shown correctly. It seems like the problem ...

Using ExpressJS with Typescript and NodeJS to serve static files is a powerful combination

Having trouble serving a static file uploaded using ExpressJS and NodeJS with Typescript as I'm encountering a 404 error. The file I need to access is located at ./src/data/uploads/test.txt, and I am attempting to reach it directly from a web browser ...

Connecting the list elements to the current state

My React component is defined as: export default class App extends React.Component<AppProps, Items> The Items class is declared as: export default class Items extends Array<Item> where Item is a class with various properties. When I direct ...

Encountering an Error While Trying to Add Typescript Support to Create React App Using Yarn

Encountering an issue while setting up a new Typescript/React project. Here's the error message: Installing template dependencies using yarnpkg... yarn add v1.22.19 [1/4] Resolving packages... [2/4] Fetching packages... error <a href="/cdn-cgi/l/em ...

What is the method for incorporating sorting into a mat-list?

I've searched for various solutions, but none seem to work with mat-list. It's crucial for me because mat-list is the only solution where drag&drop functionality works (I always face this issue with mat-table in tables and I can't find a ...

Determine the function's return type based on its arguments

Here is the code snippet: const handleNodes = (node: Node | Node[]) => { if (Array.isArray(node)) { return [{}]; } return {}; }; The desired result is: handleNodes([{}]) // infer that this returns an array handleNodes({}) // infer that this r ...

Angular tutorial: Accessing individual HTML elements within the *ngFor loop

I am facing an issue trying to access the "box-message" class using "document.querySelectorAll('.box-message')" within a tree structure where the "*ngFor" directive is utilized. After making an "http rest" request, the *ngFor directive finishes ...