What is the process for integrating custom commands in Cypress?

I have successfully implemented custom commands in Cypress and I am using Visual Studio Code as my editor. To enable IntelliSense to recognize these custom commands, I referred to this link.

In order to achieve this, I created a cypress/index.d.ts file:

/// <reference types="cypress" />
declare namespace Cypress {
interface Chainable<Subject> {
  /**
   * Do something
   * @example
   * cy.doSomething()
   */
  doSomething(): Chainable<any>
}}

After adding the index.d.ts file, now when clicking on doSomething in the spec file, it directs me to the declaration in index.d.ts. However, I am wondering if there is a way for Visual Studio Code to open the actual command implementation located under support/commands.js?

Answer №1

In response, I want to clarify that directly revealing custom commands' declaration is not endorsed (there may be exceptions). My preferred method is to organize custom commands in distinct files. For example,

File:

cypress/support/sample_command.ts

/// <reference types="Cypress" />

import * as PageElements from "../resources/selectors.json";
import * as Pages from "../resources/urls.json";

let xml: XMLDocument
let data: HTMLCollection

Cypress.Commands.add(
  "getWorkflowXML",
  (wfPath: string): Cypress.Chainable<HTMLCollection> => {
    var url = Cypress.env("url") + wfPath;

    return cy.request({
      log: true,
      url: url,
      auth: {
        user: Cypress.env("userName"),
        pass: Cypress.env("password")
      }
    }).then(response => {
      expect(response)
        .property("status")
        .to.equal(200);
      xml = Cypress.$.parseXML(response.body);
      data = xml.getElementsByTagName("java");
      return data;
    });
  }
);

declare global {
  namespace Cypress {
    interface Chainable {
      /**
       * Get Workflow XML through XHR call
       * @memberof Cypress.Chainable
       * @param wfPath
       */
      getWorkflowXML: (wfPath: string) => Cypress.Chainable<HTMLCollection>;
    }
  }
}

Then, in the cypress/support/index.js file, I would import the command file,

import './sample_command'

This approach provides better traceability, rather than directly declaring all commands under index.d.ts.

Reference:

  1. https://docs.cypress.io/api/cypress-api/custom-commands.html#Syntax
  2. https://github.com/cypress-io/add-cypress-custom-command-in-typescript

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

Exploring the integration of Glide js within a Next js environment

I am trying to figure out how to use a script tag in the next JavaScript _app.js component for utilizing the Glide JavaScript carousel. However, I am facing difficulties in using the script tag. Can someone help me out by providing guidance on how to inc ...

methods for converting and saving base64 image strings

I am using PHP to pull content from a table that includes a base64 image string. I would like to remove or drop the base64 string. Just so you know, the text and base64 image are coming from the Summernote WYSIWYG editor. I hope someone can assist me wit ...

There are two references to an object, but even if one of them is modified, the second reference continues to show the

During my attempts to troubleshoot an issue in a JS plugin, I noticed that one variable was sometimes affecting another and sometimes not. In order to investigate further, I added the following code: var a = $('#w3').data('fileinput'). ...

Observe the task while returning - Firebase Functions

I am working on a Firebase Cloud Functions project where I need to run a scraping task within one of the functions. While the scraping is in progress, I also need to provide progress updates to the consumer. For example, informing them when the task is at ...

This error occurs because the argument type 'AsyncThunkAction<any, void, {}>' cannot be assigned to a parameter of type 'AnyAction'

I encountered an error that I couldn't find a solution for on Stack Overflow The argument of type 'AsyncThunkAction<any, void, {}>' is not compatible with the parameter of type 'AnyAction'. <MenuItem onClick={() =&g ...

Next.js throws a ReferenceError when the self variable is not defined while creating a child process using a custom webpack configuration

Trying to create a child process in Next.js for a time-consuming operation. Here is the webpack configuration (next.config.js): const { merge } = require('webpack-merge'); module.exports = { webpack: (config, { buildId, dev, isServer, defaultL ...

A guide on organizing a JSON object in JavaScript/AngularJS through grouping

My JSON object contains zip code entries organized by the "Zipcode" key. My goal is to group these entries by zip code to display which zone IDs are associated with each zip code. For example, zip code 7 corresponds to zone IDs 12005, 12008, 12006, and 1 ...

React component fails to render even after successful authentication check

Trying to set up a secure route for my application, I encountered an issue with React Hooks where the state is not updated directly. This causes a problem when trying to redirect unauthenticated users, as the initial render treats them as not logged in and ...

Extract information from an external HTML table and store it in an array

I am looking for a way to extract data from an HTML table on an external site and save it as a JSON file for further manipulation. Is there a method to retrieve table data from an external HTML site that differs from the code example provided? Additional ...

Tips for transferring data to a child component's @Input using Observables

I've created an angular component that serves as a tab within a for loop on my HTML page: ... <ng-container *ngFor="let tabData of data$ | async;"> <tab-component id="{{ tabData.id }}" name="{{ tabData.name }} ...

Creating a variable as a list of string arrays in TypeScript

Currently working with Angular 2.0, I am trying to declare a variable in a Typescript file that is a list of string arrays. I attempted using yAxis_val: list, but it is not functioning correctly. If anyone knows the proper way to achieve this, please prov ...

Screening strings and arrays based on multiple criteria

My code is below and I am trying to have the bot check for two specific conditions in the user's message. The message must contain "how" plus either "doing" or "bread". It works perfectly when using only "doing" but not when adding the "bread" conditi ...

Tips for creating a striped background color on your Blogger blog's homepage

Currently, I am personalizing the default theme on Blogger called Simple Dark, but I have hit a roadblock when it comes to creating a striped background color for the posts on the homepage. Here is a glimpse of how my blog currently appears, and here is ...

What is causing the slideshows to suddenly stop functioning?

I've successfully implemented a slideshow in my project, as discussed in my previous inquiry. Although I attempted to add more slideshows using the same code and design, they are not functioning properly. Even the original slideshow has stopped worki ...

The error thrown is: "TypeError: device.devices.map is not a valid function

I encountered an error after adding products to the page and I'm having trouble identifying the cause. const {device} = useContext(Context) 91 | </div> > 92 | <div className="inner-display-collection"> | ^ ...

Embed a div element within a content-editable area

Is there a way to add a div with text to a contenteditable element and automatically select the text between the div tags after inserting the div? div.innerHTML +='<div id="id">selecttext</div>' I have tried this method, but it does ...

Retrieve JSON data from PHP using D3.request

Looking to extract data from an SQL database using PHP and then convert it into JSON format with the "echo json_encode($array);" function. I have a requirement to create a graph using D3.js, which means I need to transfer this JSON data from PHP. Can anyo ...

Error Encountered | Invalid Operation: Unable to access attributes of undefined (referencing 'CodeMirror')

Error image on chrome Using Next.js 13 Encountering an error on Google Chrome, seeking a solution to fix it or possibly just ignore it. Not utilizing Codemirror and prefer not to use it either. Tried troubleshooting methods: Deleting ".next","node_ ...

Error encountered with the {1}+ possessive quantifier in a JavaScript regex pattern

As I delve into learning Javascript and Express.js simultaneously, I decided to experiment with regular expressions while making a get request. To familiarize myself with regular expressions, I referred to this chart (also shown below). Greedy Reluctant ...

Encountering a build error in Next.js 13 when attempting to fetch an API route within a server component

I encountered an issue while building my next app (yarn run build). To troubleshoot, I created a new clean project and tested it. The problem seems to be with my route (/api/categories/route.ts) export async function GET() { return new Response(JSON.str ...