Is there a way for me to retrieve the value that has been set within the cy.get() function in Cypress using Typescript?

Is there a way to retrieve the value of the getLength function without it returning undefined? How can I access the value in this case?

Here is my code snippet:

const verifyValue = () => {
  const selector = 'nz-option-container nz-option-item';
  const myActualLength = getLength(selector);
  console.log('I need to extract this value: ' + myActualLength);
}

const getLength = (selector: string) => {
  let length;
  cy.get(selector).then((listItem) => {
    length = listItem.length;
  })
  return length;
}

Answer №1

Here is a simple way to retrieve the value:

const findLength = (element: string) => {
  let size;
  cy.get(element).then((item) => {
    size = item.length;
  })
  return cy.wrap(size);
}

findLength(element).then(result => {
  console.log('This is the value I am looking for: ' + result);
})

Answer №2

Based on my knowledge of cypress (and javascript callbacks), it is necessary to return the value from within the .then() function. Attempting to access the value outside of this function will result in undefined.

Therefore, you could try:

cy.get(target).then((element) => {
   return element.length;
})

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

Ensure that the key and value types in a Typescript Map are strictly specified

Is it feasible to generate a map that consists of key-value pairs, where the key is represented by a string and the value corresponds to an object containing specific properties defined by mapValue? type mapValue { first: string; second: boolean; } Yo ...

Failed validation for Angular file upload

I attempted to create a file validator in the front end using Angular. The validator is quite straightforward. I added a function onFileChange(event) to the file input form to extract properties from the uploaded file. I then implemented a filter - only al ...

A Guide to Filtering MongoDB Data Using Array Values

I am trying to extract specific data from a document in my collection that contains values stored in an array. { "name": "ABC", "details": [ {"color": "red", "price": 20000}, {" ...

Implementing TypeScript type declarations for merging core types

Is there a way to perform type declaration merging in TypeScript for built-in types when using imports? I am currently attempting to merge interfaces as per the guidelines outlined in this documentation: https://www.typescriptlang.org/docs/handbook/declar ...

When utilizing a generic type with a class, type T fails to meet the specified constraint

export type ExtractType<T extends Array<{ name: Array<string>, type: keyof TypeMapping }>> = { [K in T[number]['name'][0]]: TypeMapping[Extract<T[number], { name: K }>['type']] } export class CommandLineParse ...

Overlooking errors in RxJs observables when using Node JS SSE and sharing a subscription

There is a service endpoint for SSE that shares a subscription if the consumer with the same key is already subscribed. If there is an active subscription, the data is polled from another client. The issue arises when the outer subscription fails to catch ...

Type inference error in TypeScript occurs within a conditional statement when the condition relies on the output of a function call rather than a boolean expression

In my TypeScript code, I have a Linked List class that is working perfectly. The class includes a Node type and functions to add items to the list. type ListItem = number | string | object; class Node { private value: ListItem; private next: Node | nu ...

Unable to perform a union operation that combines multiple enums into one

Here is a basic example: export enum EnumA { A = 'a', } export enum EnumB { A = 'b', } export class SomeEntity { id: string; type: EnumA | EnumB; } const foo = (seArray: SomeEntity[]) => { seArray.forEach((se) => { ...

ESLint and Prettier are butting heads when trying to run their commands consecutively

My package.json file includes two commands: "format": "prettier --write \"{src,{tests,mocks}}/**/*.{js,ts,vue}\"", "lint": "eslint . -c .eslintrc.js --rulesdir eslint-internal-rules/ --ext .ts,.js,.vue ...

In order to emphasize the chosen list item following a component refresh

SCENARIO: Let's consider a scenario where I have a component named list, responsible for displaying a list of all customers. Within this list, certain conditions are set up as follows: 1) Initially, the 1st list-item (e.g. Customer 1) is selected by ...

Error displaying messages from the console.log function within a TypeScript script

My node.js application runs smoothly with "npm run dev" and includes some typescript scripts/files. Nodemon is used to execute my code: This is an excerpt from my package.json file: { "scripts": { "start": "ts-node ./src/ind ...

I encountered TS2300 error stating a duplicate identifier appeared once I transferred my code to Angular CLI

Currently undergoing the process of transitioning our code to Angular CLI for our hybrid app. The plan is to migrate the Angular part to CLI while the AngularJS portion continues to be handled by custom Webpack. It's worth noting that both parts (Angu ...

Adjust the transparency and add animation effects using React JS

When working on a React project, I encountered an issue where a square would appear under a paragraph when hovered over and disappear when no longer hovered. However, the transition was too abrupt for my liking, so I decided to implement a smoother change ...

Is there a way to define an object's keys as static types while allowing the values to be dynamically determined?

I am attempting to construct an object where the keys are derived from a string union type and the values are functions. The challenge lies in wanting the function typings to be determined dynamically from each function's implementation instead of bei ...

Testing Next.js's getServerSideProps function with Jest: A Step-by-Step Guide

I want to conduct Jest and Enzyme tests on the Next.js getServerSideProps function. This function is structured as follows: export const getServerSideProps: GetServerSideProps = async (context) => { const id = context?.params?.id; const businessName ...

Is there a more efficient method for providing hooks to children in React when using TypeScript?

My component structure looks something like this: Modal ModalTitle ModalBody FormElements MySelect MyTextField MyCheckbox DisplayInfo ModalActions I have a state variable called formVars, and a function named handleAction, ...

Guidelines for segregating a Union from an Array

I'm currently utilizing graphql-code-generator to automatically generate TypeScript definitions from my GraphQL queries. I have a specific union within an array that I am trying to extract in TypeScript. Is this feasible? Although I came across an exa ...

Utilizing an external TypeScript class without the need for importing it

Let's consider a scenario where we have a class named Constant. The requirement is to make this class accessible globally without the need for importing, is there a way to achieve this? In the constant.ts file: class Constant { public stati ...

Seeking a solution to the useRef problem. Encountering difficulties with React Hook useRef functionality within a NextJS application

Whenever I refresh the page, the 'Ref' value is displayed as null. This causes the if condition blocks not to work. I attempted to modify the useRef values but could only set it to null. When I console log the myDivRef.current, it returns "Ref: ...

TS1086: Attempting to declare an accessor within an ambient context is not allowed

While using Angular, I encountered the error TS1086: An accessor cannot be declared in an ambient context. when using Javascript getters and setters in this Abstract Typescript class. Here is the code snippet causing the issue: /** * The current id ...