Cypress terminal issue: Cannot find property in 'cy & CyEventEmitter' type

Tech stack: Angular v15 and Cypress V12

Despite successful runs of my component and end-to-end tests, I encounter peculiar terminal errors while running the tests.

The issue could potentially stem from my Cypress configuration for shared commands.

Here are my shared commands:

declare global {
  namespace Cypress {
    interface Chainable {
      loginAs(role?: string): Chainable<any>,
      isWelcomePage(): Chainable<any>,
      openMenu(): Chainable<any>,
    }
  }
}

Cypress.Commands.add('loginAs', (role?: string) => {
  const user = Cypress.env('user');
  cy.visit(Cypress.env('local'));
  cy.get('#mat-input-0', { timeout: 30000 }).should('be.visible').type(user.email);
  cy.get('#mat-input-1', { timeout: 30000 }).should('be.visible').type(user.password);
  cy.get('.btn').click({ force: true });
});

This is my cypress configuration:

import { defineConfig } from "cypress";
const { verifyDownloadTasks } = require('cy-verify-downloads');

export default defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      on('task', verifyDownloadTasks)
    },
    specPattern: "cypress/e2e/**/*.cy.ts",
  },
  chromeWebSecurity: false,
  screenshotsFolder: "cypress/snapshots",
  trashAssetsBeforeRuns: true,
  viewportWidth: 1400,
  viewportHeight: 1200,
  video: false,
  defaultCommandTimeout: 10000,
  env: {
    local: "http://localhost:4200/",
    staging: "hidden",
    backend: "hidden",
    user: {
      email: "hidden",
      password: "hidden",
    },
  },
  component: {
    devServer: {
      framework: "angular",
      bundler: "webpack",
    },
    specPattern: "**/*.cy.ts",
  },
});

This is the terminal errors:

https://i.sstatic.net/3qBnk.png

Exact error messages

  • Property 'loginAs' does not exist on type 'cy & CyEventEmitter'.

Current Attempt:

Tsconfig:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "forceConsistentCasingInFileNames": true,
    "strict": false,
    "noImplicitOverride": true,
    "noPropertyAccessFromIndexSignature": false,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "ES2022",
    "module": "es2020",
    "allowJs": true,
    "lib": [
      "es2020",
      "dom"
    ],
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "types": ["cypress", "cy-verify-downloads"],
  },
  "angularCompilerOptions": {
    "enableI18nLegacyMessageIdFormat": false,
    "strictInjectionParameters": false,
    "strictInputAccessModifiers": false,
    "strictTemplates": false
  },
  "include": [
    "./src",
    "./cypress/support/index.d.ts"
  ]
}

index.d.ts file:

/// <reference types="cypress" />
export { }

declare global {
  namespace Cypress {
    interface Chainable {
      loginAs(role?: string): Chainable<any>,
      isWelcomePage(): Chainable<any>,
      openMenu(): Chainable<any>,
    }
  }
}

Similar terminal errors crop up when attempting to run component tests.

https://i.sstatic.net/fJKY1.png

Answer №1

We can approach this problem in a few different ways, but here's one suggestion:

  • Start by placing the custom command types in cypress/support/index.d.ts

  • Include a reference to the base Cypress types

  • Transform the .d.ts file into a module with a dummy export

/// <reference types="cypress" />
export {}

declare global {
  namespace Cypress {
    interface Chainable {
      loginAs(role?: string): Chainable<any>,
      isWelcomePage(): Chainable<any>,
      openMenu(): Chainable<any>,
    }
  }
}

Don't forget to include your index.d.ts file in the tsconfig.json

{
  ...
  "include": [ "./src/app", "./cypress/support/index.d.ts"],
}

Answer №2

There was a time when I encountered a similar issue, only to realize that the type definition was actually correct, but the placement was off.

In my situation, I utilized NextJS to incorporate custom or adjustable types. Usually, Cypress would generate a folder called support/commands.ts, where you could input the specific type you wanted to define.

Don't forget to include your Cypress function!

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

Testing React Components - The `useClient` function should only be used within the `WagmiConfig` component

In my Next.js app with TypeScript, Jest, and React testing library, I encountered an error while trying to test a component. The error message states that `useClient` must be used within `WagmiConfig`. This issue arises because the `useAccount` hook relies ...

How to Utilize Knockout's BindingHandler to Integrate JQuery.Datatables Select Feature?

I've developed a custom KO bindingHandler (view it here) to assist in updating the DataTable. The documentation for JQuery.DataTable.Select regarding how to access data requires a handle. You can see the details here. var table = $('#myTable&a ...

What steps should I take to verify the validity of an Angular form?

I am struggling with validating an inscription form in HTML. Despite trying to implement validations, the inputs are still being saved in the database even when they are empty. Here are the validations I want to include: All inputs are required Email addr ...

JavaScript for generating horizontal bar charts in Angular

I am looking to create a horizontal bar dataset with only positive values and the y-axis line positioned in a specific way. I want it to look like this image, but unfortunately I am getting results that are not what I need, like shown in this example. Ne ...

Utilize components with dynamic identifiers for enhanced versatility - Angular 4

Is it possible to use the map.component within my dynamic window.component multiple times in different windows? Each time a click event triggers the creation of a new dynamic window with a map component inside. Here's an example: window.component.htm ...

Discover the process of implementing nested service calls in Angular 2 by utilizing observables

Here are my component file and service file. I am trying to achieve that after the verification() service method is successfully called, I want to trigger another service method signup() within its success callback inside subscribe. However, I am encounter ...

Updating view with *ngIf won't reflect change in property caused by route change

My custom select bar has a feature where products-header__select expands the list when clicked. To achieve this, I created the property expanded to track its current state. Using *ngIf, I toggle its visibility. The functionality works as expected when cli ...

Tips for styling the value of a control in an Angular Reactive Form

What is the best way to format a value in an Angular Form Control? For example, if I have a date field returned from a database with seconds and milliseconds included, how can I format it to show only day, month, year, etc. similar to using the date pipe? ...

The onNodeContextMenuSelect function does not seem to be functioning properly within the p-tree

<p-tree [value]="files" selectionMode="single" (onNodeContextMenuSelect)="showContect($event)" > </p-tree> Whenever I right click, the event doesn't seem to be triggering. Instead, the default browser c ...

What are the steps for implementing the Ionic 2 Pulling Refresher feature in my application?

Hey everyone, I'm currently working on developing a mobile app using AngularJS 2/Ionic2. I am facing an issue with implementing a pull-to-refresh feature in my app. We followed the steps outlined in this link, and while we were able to get the page to ...

Displaying a component within an ngFor loop

During my iteration over an array of objects, I encountered a situation where I needed to specify a component to load within the object. For instance, one of the items in the loop looks like: { label: 'Patient\'s Weight', subtitle ...

Angular: Streamlining Pagination using Bootstrap Styles

I need help with adding pagination to my table. I've been following the instructions on this link: Pagination Tutorial However, I encountered an error while trying to use map(product,i). The specific error message is: Property 'map' does ...

What is the rationale behind assigning a random value to the `(keyup)` event in order to update template local variables in Angular2?

To update #box in <p>, I need to give a random value to the (keyup) attribute. Here's an example: <!-- The value on the right of equality sign for (keyup) doesn't matter --> <input #box (keyup)="some_random_value" placeholder ...

Issue with Adding Additional Property to react-leaflet Marker Component in TypeScript

I'm attempting to include an extra property count in the Marker component provided by react-leaflet. Unfortunately, we're encountering an error. Type '{ children: Element; position: [number, number]; key: number; count: number; }' is n ...

Provide a TypeScript interface that dynamically adjusts according to the inputs of the function

Here is a TypeScript interface that I am working with: interface MyInterface { property1?: string; property2?: string; }; type InterfaceKey = keyof MyInterface; The following code snippet demonstrates how an object is created based on the MyInter ...

"Encountering an error with the any type in the useLocation feature while using React Router version 6

https://i.sstatic.net/0YcS9.png What steps should I take to resolve this particular type of error issue? My attempt at passing a custom type did not yield successful results. ...

Obtain the content window using angularJS

I've been attempting to retrieve the content window of an iframe element. My approach in JQuery has been as follows: $('#loginframe')[0].contentWindow However, since I can't use JQuery in Angular, I've been trying to achieve thi ...

The Intl.DateTime formatter consistently generates incorrect times even after refreshing the component in a React application

Our component is responsible for receiving information from the backend and rendering it. The properties of the component are defined as: interface CitizenshipProps { citizenship?: Citizenship; name?: string; lastName?: string; onUpdateClic ...

Tips on inferring a distinct generic type for every element within an array of objects

I'm working on code that creates a timeline chart for data. I want the code to accept an array of series, each containing data and various getters used to position and render the data on the chart. Below is a simplified example of the code. The actua ...

Ways to leverage a single observable to modify a second one

I'm facing an issue while trying to utilize an observable favourites$ in order to construct another array of the same type. I am anticipating that the favourites$ observable will be filled with an array of type University, and then I can update a clas ...