The argument type 'string' does not match the parameter type 'keyof Chainable' in Cypress JavaScript

Trying to incorporate a unique custom command in Cypress (commands.js file) as follows:

     Cypress.Commands.add("login", (email, password) => {
      cy.intercept('POST', '**/auth').as('login');
      cy.visit('/auth');
      cy.get('[formcontrolname="email"]').type(email);
      cy.get('[formcontrolname="password"]').type(password);
      cy.get('form').submit();
      cy.wait('@login').then(xhr => {
        expect(xhr.request.body.email).to.equal(email);
        expect(xhr.request.body.password).to.equal(password);
       });
    });

An error is encountered with the message:

'Argument type string is not assignable to parameter type keyof Chainable ...   Type string is not assignable to type "and" | "as" | "selectFile" | "blur" | "check" | "children" | "clear" | "clearCookie" | "clearCookies" | "clearLocalStorage" | "click" | ...     Type string is not assignable to type "intercept"'

A relevant question can be found here Argument type string is not assignable to parameter type keyof Chainable... in Cypress, however, the solutions presented apply solely to an index.d.ts file, whereas I am working with an index.js file for cypress version 10.3.0. Any assistance on resolving this issue would be greatly appreciated.

Answer №1

Avoid mixing .js and .ts files in your Typescript project.

Convert everything to .ts, then include an index.d.ts file with type definitions for any custom commands.

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

declare namespace Cypress {
  interface Chainable<Subject = any> {
    login(): Chainable<any>;
  }
}

You might encounter issues, so make sure to have a tsconfig.json file in the /cypress folder.

If uncertain, refer to cypress-realworld-app for guidance on setting up Typescript.

Answer №2

The solution provided resolved two Linting-issues for me:

'Subject' is defined but never used. eslint(@typescript-eslint/no-unused-vars)
and
Unexpected any. Specify a different type. (eslint@typescript-eslint/no-explicit-any)
. The fix that worked without triggering any Linting-issues was:

// support/index.d.ts
/// <reference types="cypress" />

declare namespace Cypress {
  interface Chainable {
    login(name: string): void;
  }
}

With this, TypeScript now correctly infers parameter types when defining commands:

https://i.sstatic.net/8EptO.png

However, there is still an issue with proper typing for the return type. For instance, the following code does not produce a TypeScript error even though the return type is incorrect (it should be void as per the declaration):

Cypress.Commands.add("login", (name) => {
  return name;
})

To enforce type-checking for the return type as well, you can do the following:

// declare the function explicitly
const login: Cypress.Chainable["login"] = (name) => {
  // will trigger an error now
  // return name;
  return;
};

Cypress.Commands.add("login", login);

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

typescriptCreating a custom useFetch hook with TypeScript and Axios

I have a query regarding the utilization of the useFetch hook with TypeScript and Axios. I came across an example of the useFetch hook in JavaScript, but I need help adapting it for TypeScript. The JavaScript implementation only handles response and error ...

React Native's fetch function appears to be non-responsive

I am experiencing an issue where the fetch function does not seem to fire in my React Native component: import { Button } from 'react-native'; export function Test() { function submit() { console.log('submit'); fetch('h ...

AngularJS input range is written inside the bubble that crosses over the screen

Is there a way to write inside the bubble of the range slider? I have adjusted the design of the range slider and now I simply want to display the number inside the bubble: Please see image for reference I aim to display the number inside a circle. What ...

AngularJS redirection to a different state by utilizing a URL

When I need to direct a user to a specific state, typically I would use the following code: $state.go('state_name'); $state.transitionTo('state_name'); This method usually takes users to /state_name. However, there is one particular s ...

Unable to scroll to the top of the page with JavaScript

I tried the code below but it didn't quite do the trick. Can someone assist me with refreshing the page to the top every time it loads? window.addEventListener('load', function(){ window.scrollTo(0,0) }) window.onload = (event) => { ...

Ways to resolve the issue: ""@angular/fire"' does not contain the exported member 'AngularFireModule'.ts(2305) in an ionic, firebase, and

I am facing an issue while attempting to establish a connection between my app and a firebase database. The problem arises as I receive 4 error messages in the app.module.ts file: '"@angular/fire"' has no exported member 'AngularFi ...

Enhance the appearance of rows in a table by adding a captivating marquee effect to those with

I'm working with a table that has 7 rows and 2 tabs for Sunday and Monday. The row corresponding to the current time is highlighted in red. I wanted to know if it's possible to add the following <marquee>My first Row</marquee> effe ...

Utilize React-Charts.js-2 with ChartJS to create a customized bar chart

When creating bar graphs based on monthly data, everything works fine expect for the fact that the order of the months is not maintained and it appears mixed up in each rendering. The API provides the following data: { { "_id": 2022, &qu ...

Utilize CSS to format the output of a script embedded within

When I embed the following script in my HTML, the output doesn't have any styling. How can I style the script output to blend well with the existing HTML structure? I tried accessing the output by ID, but couldn't figure it out. <script> ...

Utilizing data from the home component in another component: A guide

Here is the code I am working with, showcasing how to utilize (this.categoryType) in another component: getCategoryDetails(){ return this.http.get('ip/ramu/api/api/…') .map((res:Response) => res.json()); } The above code snippet is utilize ...

Is there a specific index range in javascript or nodejs for accessing array items?

I recently came across this Ruby code snippet: module Plutus TAX_RATES = { (0..18_200) => { base_tax_amount: 0, tax_rate: 0 }, (18_201..37_000) => { base_tax_amount: 0, tax_rate: 0.19 }, (37_001..80_0 ...

Updating HTML content based on an active user session using Node.js/Express - A Step-by-Step Guide

I'm struggling to find a way to remove the login/signup buttons once a user has successfully logged in. The issue lies within my header file that needs some modification. <section class="header"> <div class="wrapper"> <nav ...

Capturing Data from Tables and Saving it with Protractor

Imagine having a table structured like this <h2>HTML Table</h2> <table> <tr> <th>Company</th> <th>Contact</th> <th>Code</th> </tr> <tr> <td>Alfreds Fu ...

Tips on keeping Bootstrap Modals out of your browsing history

Imagine this scenario A visitor lands on Page A, clicks through to Page B, and then engages with a link that triggers a modal (code provided below) <a href="mycontent.html" data-target="#modal_xl" data-toggle="modal" data-backdrop="static">Click me ...

When incorporating a JS React component in TypeScript, an error may occur stating that the JSX element type 'MyComponent' is not a valid constructor function for JSX elements

Currently, I am dealing with a JavaScript legacy project that utilizes the React framework. Within this project, there are React components defined which I wish to reuse in a completely different TypeScript React project. The JavaScript React component is ...

Is there a way to cancel hiding on a q-dialog?

I'm currently working on integrating a confirmation modal within a dialog box that includes form input fields. The purpose is to alert the user when they try to exit without saving their changes. The modal should appear every time the user modifies th ...

What action is triggered on an Apple iPhone when a notification is tapped?

Currently, I am working on a React application and testing it on an Apple mobile phone. One issue I encountered is that when I receive an SMS, the number appears as a suggestion above the keyboard. I want to be able to tap on this number and have it automa ...

What could be causing my Vue component to not refresh?

Can anyone help me figure out why this component isn't re-rendering after changing the value? I'm attempting to create a dynamic filter similar to Amazon using only checkboxes. Here are the 4 components I have: App.vue, test-filter.vue, filtersIn ...

A comprehensive guide on using HttpClient in Angular

After following the tutorial on the angular site (https://angular.io/guide/http), I'm facing difficulties in achieving my desired outcome due to an error that seems unclear to me. I've stored my text file in the assets folder and created a config ...

Sending Multiple Sets of Data with Jquery Ajax.Post: A Step-by-Step Guide

I am currently working with asp.net mvc and I have a requirement to send two sets of database information from jQuery to my Mvc view. Here is an example of how my view looks like: public ActionResult MyView(Product one, Product two) { } Now, my question ...