The correct method for recording a personalized directive with added functionality using the then function

Here's a full Typescript Cypress project.

Encountering an error while trying to use the custom command below:

Usage:

    cy.restGetUserId(userEmail).then(userId => {
        //do something with userId
    });

Custom command:

Cypress.Commands.add('restGetUserId', (userEmail) => {
    expect(userEmail).to.not.equal(undefined);

    cy.request({
        //some request, works!
    }).then((response) => {
        cy.wrap(response.body.id);
    });
});

Current documentation:

    /**
     * also works as a normal user
     *
     * @example cy.restGetUserId('<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1b6874767e5b7e767a727735787476">[email protected]</a>');
     * @param userEmail - get the userId from this email
     * @returns the id of the given email/user.
     */
    restGetUserId(userEmail: string): string;

The error most likely lies in the documentation of this method. What is the best way to document this method properly, especially focusing on the return value?

Answer №1

When creating a custom command, it is important to note that it can only return Chainable<T>. Here is an example of a valid type definition for your reference:

   restGetUserId(userEmail: string): Chainable<string>;

Answer №2

If you wish to continue utilizing a specific element or data generated by your custom command in Cypress, you must ensure that the chain of commands that fetches the item is returned.

To achieve this, follow these steps:

Cypress.Commands.add('getUserDetails', (userEmail) => {
    expect(userEmail).to.not.equal(undefined);

    return cy.request({
        //make a request, it works!
    }).its('response.body.id') // retrieve the required id
});

Now you can access the id obtained from the request.

cy.getUserDetails(userEmail).then(cy.log) //logs the id fetched from the request

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 is the method for adding local images to FormData in Expo version 48 and above?

When working with Expo v47 and its corresponding React Native and TypeScript versions, FormData.append had the following typing: FormData.append(name: string, value: any): void An example of appending images using this code could be: const image = { uri ...

Dynamic addition of script to <head> element in Angular is a common task for many developers

I have explored some examples that illustrate how to dynamically add a script with a URL in Angular However, I am interested in adding this type of content to the <head> <script> !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(! ...

Exploring the Node environment setup within Nest.js

Currently, I am in the midst of setting up a Nest.js project and seeking an efficient solution for defining the Node environment used by the ConfigService to load environment variables: import { Module } from '@nestjs/common'; import { ConfigSer ...

Troubleshooting Puppeteer compatibility issues when using TypeScript and esModuleInterop

When attempting to use puppeteer with TypeScript and setting esModuleInterop=true in tsconfig.json, an error occurs stating puppeteer.launch is not a function If I try to import puppeteer using import * as puppeteer from "puppeteer" My questi ...

Dealing with the possibility of an empty array when accessing elements by index in Typescript

What is the best way to handle accessing elements by index in an array in Typescript when the array can be empty, resulting in potentially undefined elements? I am developing a simple game using React and Typescript where I have a variable named game whic ...

Directing users to varying pages based on a particular criteria

As we continue to develop our application, we are creating various pages and need to navigate between them. Our current framework is Next.js. The issue we are facing involves the Home page: when transitioning from the Home page to another page (such as pa ...

Mysterious attributes of angular 6's <table mat-table> tag

This particular question regarding the angular material table has not been duplicated in any other discussions. Other similar questions pertain to angular versions 2-5, not version 6 The issue I am encountering is as follows: Can't bind to 'dat ...

Utilize Typescript to inject types into a library

I have a code snippet that reads data from a JSON file and creates a type based on it, which is then used for further operations. import jsonData from './mydata.json' type CustomType = typeof jsonData .... This process ensures that the generate ...

Issue encountered: XHR error (404 Not Found) occurred following the installation of typescript-collection in Angular 2 final version

After setting up an Angular 2 project quickly, I added the typescript-collections package using the command: npm install typescript-collections --save However, upon launching my project, I encountered the following error: GET http://localhost:63342/IMA% ...

Filtering a Table with Angular Material: Using multiple filters and filter values simultaneously

Looking to implement dual filters for a table of objects, one being text-based and the other checkbox-based. The text filter works fine, but struggling with the checkbox filter labeled "Level 1", "Level 2", etc. Ideally, when a checkbox is checked, it shou ...

When trying to access the "form" property of a form ElementRef, TypeScript throws an error

I've encountered an issue with accessing the validity of a form in my template: <form #heroForm="ngForm" (ngSubmit)="onSubmit()"> After adding it as a ViewChild in the controller: @ViewChild('heroForm') heroForm: ElementRef; Trying ...

Material UI offers a feature that allows for the grouping and auto-completion sorting

I am currently utilizing Material UI Autocomplete along with React to create a grouped autocomplete dropdown feature. Here is the dataset: let top100Films = [ { title: "The Shawshank Redemption", genre: "thriller" }, { title: " ...

What are the TypeScript type definitions for the "package.json" configuration file?

What is the most efficient method for typing the content of the "package.json" file in TypeScript? import { promises as fs } from 'fs'; export function loadManifest(): Promise<any> { const manifestPath = `${PROJECT_DIR}/package.json`; ...

Leverage the generic types of an extended interface to simplify the creation of a shorthand type

Attempting to streamline my action shorthand that interacts with AsyncActionCreators. A function has been crafted to accept a React dispatch: Dispatch<T> parameter: const fetchProfileAction = actionCreator.async<void, Profile, any>('FETC ...

Error encountered during Svelte/Vite/Pixi.js build: Unable to utilize import statement outside of a module

I'm currently diving into a project that involves Svelte-Kit (my first venture into svelte), Vite, TypeScript, and Pixi. Whenever I attempt to execute vite build, the dreaded error Cannot use import statement outside a module rears its ugly head. Desp ...

What is the best way to ensure that my variables are properly differentiated in order to prevent Angular --prod --aot from causing empty values at runtime?

While testing my code locally in production, the functions I've written are returning the expected values when two parameters are passed in. However, after running ng build --prod --aot, the variable name within the functions changes from name to t. ...

Angular is programmed to detect any alterations

Upon detecting changes, the NgOnChanges function triggers an infinite service call to update the table, a situation that currently perplexes me. Any assistance on this matter would be greatly appreciated. Many thanks. The TableMultiSortComponent functions ...

Step by step guide on integrating current locations in Leaflet OpenStreetMap within an Angular application

I am currently working on an Angular application that incorporates a map using Leaflet OpenStreetMap. I want to display the real-time latitude and longitude for the map, which should update based on the location. Can someone advise me on how to add the cur ...

Using string interpolation and fetching a random value from an enum: a comprehensive guide

My task is to create random offers with different attributes, one of which is the status of the offer as an enum. The status can be “NEW”, “FOR_SALE”, “SOLD”, “PAID”, “DELIVERED”, “CLOSED”, “EXPIRED”, or “WITHDRAWN”. I need ...

Sanity.io and using images with next/image extension glitch

Hello everyone, I'm excited to join Stack Overflow for the first time. Currently, I am working on a project using Next.js with Sanity as my headless CMS. I have come across what appears to be a TypeScript type issue. Here is the link to the code on Gi ...