I encountered an issue with Cypress when attempting to utilize a custom command. The error message "TypeError cy.login is not a function" keeps popping up. Any suggestions on how to resolve this

I am currently working on a TypeScript project and I am attempting to write some tests using Cypress.

However, I encountered the following error: TypeError - cy.login is not a function. This error occurred during a before each hook, so we are skipping the remaining tests in the current suite related to the Dashboard page when trying to call the custom command cy.login()

This is the code for the custom command:

// support/index.ts

Cypress.Commands.add("login", (email, password) => {
  cy.request("http://localhost:3000/login", {
    email,
    password,
  }).then((r) => {
    window.localStorage.setItem("access", r.body.access);
    window.localStorage.setItem("refresh", r.body.refresh);
  });
});

// cypress/global.d.ts

declare global {
  namespace Cypress {
    interface Chainable {
      /**
       * Custom command to select DOM element by data-cy attribute.
       * @example cy.dataCy('greeting')
       */
      dataCy(value: string): Chainable<Element>;

      login(username: string, password: string): Chainable<string>;
    }
  }
}

// cypress/e2e/dashboard.spec.cy.ts

describe("Dashboard page", () => {
  beforeEach(() => {
    cy.login("<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="234f4a41424d0d57465057121363444e424a4f0d404c4e">[email protected]</a>", "password");
  });

  it("should actually be accessible", () => {
    cy.visit("/dashboard");
  });
});

Answer №1

When defining the namespace in a *.d.ts file, it is important to include the new types "./support" identifiers within the tsconfig.json file.

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["es5", "dom"],
    "types": ["cypress", "./support"]
  },
  "include": ["**/*.ts"]
}

Adding "./support" to the tsconfig.json file allows TypeScript to locate a declaration file (the *.d.ts file) within the specified directory.

Alternatively, you can also add:

<reference types="../support"/>

to each file that needs the new custom command, although this approach may be somewhat repetitive.

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

Setting up systemjs.config.js for utilizing relative paths within IIS - A step-by-step guide

My new ASP.NET MVC web application utilizes Angular for its UI components. I have set up the necessary config files in my project (e.g. package.json and systemjs.config.js). Created a test page Index.cshtml to test out the template in app.component.ts. The ...

Setting options using the form group in dropdowns in Angular can greatly enhance the user experience

I have created a FormGroup called holidayform and set it up as follows: holidayform: FormGroup; this.holidayform = this.fb.group({ title: ['', [Validators.required]], entryDate: ['',], }) this.holidayform.patchValue ...

Error in Typescript occurring with a custom typography element

I recently developed a simple typography component for my React project and it's causing a Typescript error that's puzzling me a bit. Typography Component Code import clsx from 'clsx'; const sizeVariants = { h1: 'h1', ...

NodeJS function does not pause for the PostgreSQL database call despite using await keyword

I am attempting to recursively insert entries into the database where each entry depends on the previous one (the ID of the previous entry will be the child_id of the next entry). However, I am facing difficulties in getting async/await to work correctly. ...

What if we had webpack disregard certain syntactic enhancements?

For instance: using optional chaining The application I'm working on is strictly for internal use, and it's specifically optimized for the latest Chrome browser. This means I can take advantage of syntactic sugar without needing to compile it, w ...

Tips for setting up Code Coverage in a Cypress environment for testing a NextJS build simultaneously

We are currently exploring the possibility of integrating code coverage into our setup utilizing cypress and nextjs. Within our cypress configuration, we utilize the next() function to mimic backend requests within nextjs. The cypress.config.ts file is st ...

The spread operator seems to be malfunctioning whenever I incorporate tailwindcss into my code

Hi there! I hope you're doing well! I've come across a strange issue in Tailwindcss. When I close the scope of a component and try to use props like ...rest, the className doesn't function as expected. Here's an example: import { Butto ...

What is the proper way to utilize useRef in TypeScript to assign a function to ref?

I am just diving into Typescript and I am looking to assign a function to a ref within a custom hook. My goal is for the function to remain constant throughout renders. Check out the code on CodeSandbox: https://codesandbox.io/s/918l0wro4r function runFu ...

Could you confirm if this is a TypeScript function?

Recently, while delving into the vue-next source code, I stumbled upon a particular line that left me puzzled. Due to my limited experience with TypeScript, I found myself struggling to grasp its purpose. Could someone clarify if this snippet constitutes ...

Importing TypeScript modules dynamically can be achieved without the need for Promises

I find myself in a scenario where the dynamic nature of these commands is crucial to prevent excessive loading of unnecessary code when executing specific command-line tasks. if (diagnostics) { require('./lib/cli-commands/run-diagnostics').run ...

Typescript encounters a failure in typing when an object is destructured

There is a function that returns an object with two properties (res, mes) where one of them could be null: const fetchJSON = <Res, Body>(link: string, body: Body): Promise<{ res: Res; mes: null } | { res: null; mes: Popup }> => { return n ...

Issue with ngx-extended-pdf-viewer when using URL

I'm struggling to display my PDF file on a viewer using a URL in TypeScript. I am utilizing ngx-extended-pdf-viewer. Below is a snippet of my code with the URL replaced: <ngx-extended-pdf-viewer *ngIf="!isFirefox" [src]="'http://www.chi ...

Commit to calculating the total sum of each element using AngularJS

Trying to implement a like counter using Facebook's GRAPH API. I have a list of object IDs and for each ID, I make an API call to retrieve the number of likes and calculate a total. The issue arises as the API call returns a promise, causing only one ...

What is the proper way to create a generic class that can produce various output types while implementing a basic interface?

An abstract class is being created here to transform one type of object into another, with a simple interface comprising id:string and type:string. The intention behind the class definition is to emphasize that it will produce an assembly and during insta ...

Converting a nested JSON object into a specific structure using TypeScript

In the process of developing a React app with TypeScript, I encountered a challenging task involving formatting a complex nested JSON object into a specific structure. const data = { "aaa": { "aa": { "xxx&qu ...

Step-by-step guide for resolving the issue of "Observable.share is not recognized as a function" in Angular 2

When working with cache structure in Ionic 2, I often encounter an error when defining an observable array to store data retrieved from the server. How can I troubleshoot this issue and resolve it? marketArray : Observable<any>; /* GLOBAL */ th ...

Next.js is having trouble identifying the module '@types/react'

Every time I attempt to launch my Next.js app using npm run dev, an error notification pops up indicating that the necessary packages for running Next with Typescript are missing: To resolve this issue, kindly install @types/react by executing: np ...

Tips for incorporating a fresh variant into the default typography of MUI using TypeScript

While following the official MUI instructions here, a question arose. To customize the primary color in the file newTheme.ts and add a new variant type post: import { createTheme } from "@mui/material"; const newTheme = createTheme({ palette ...

The standard category of class method parameter nature

I'm encountering difficulties when attempting to correctly define a method within a class. To begin with, here is the initial class structure: export class Plugin { configure(config: AppConfig) {} beforeLaunch(config: AppConfig) {} afterSe ...

Display Bootstrap Modal using Typescript in Angular

Looking for some creative ideas here... My Angular site allows users to register for events by filling out a form. They can also register themselves and other people at the same time. https://i.sstatic.net/a44I7.png The current issue ~ when a user clicks ...