Leveraging the cypress chainable command within an if/else statement

Can anyone offer guidance on how to incorporate chainable commands with if/else logic without duplicating code? Specifically, I want to avoid repeating

.trigger('focus', {force: true}).click({force: true});
in both the if and else statements. I have tried using return in the logic but it's not working as expected.

    const selectedOption = 'I am option'
    cy.get('.my-selector')
      .contains(selectedOption)
      .scrollIntoView()
      .then(($option) => {
        if ($option.find('input').length === 1) {
          cy.wrap($option.find('input')).trigger('focus', {force: true}).click({force: true});
        } else {
          cy.wrap($option).trigger('focus', {force: true}).click({force: true});
        }
      });

utilizing return

      .then(($option) => {
        if ($option.find('input').length === 1) {
          return cy.wrap($option.find('input'));
        }

Answer №1

If you want to retrieve the correct target, consider creating a helper function for that,

const getTarget = ($el) => {
  const $input = $el.find('input');
  return $input.length ? $input : $el;
}

cy.get('.my-selector')
  .contains(selectedOption)
  .scrollIntoView()
  .then(($option) => {
    cy.wrap(getTarget($option)).trigger('focus', {force: true}).click({force: true});
  });

// alternative syntax

cy.get('.my-selector')
  .contains(selectedOption)
  .scrollIntoView()
  .then($option => getTarget($option))
  .trigger('focus', {force: true}).click({force: true});

Alternatively, you can achieve this with a custom command

Cypress.Commands.add('optionTarget', { prevSubject: true }, (subject) => {
  const $input = subject.find('input');
  return $input.length ? $input : subject;
})

cy.get('.my-selector')
  .contains(selectedOption)
  .scrollIntoView()
  .optionTarget().trigger('focus', {force: true}).click({force: true});

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

Challenges encountered while deploying a NextJS project with TypeScript on Vercel

Encountering an error on Vercel during the build deploy process. The error message says: https://i.stack.imgur.com/Wk0Rw.png Oddly, the command pnpm run build works smoothly on my PC. Both it and the linting work fine. Upon inspecting the code, I noticed ...

TypeScript encountering difficulty in locating types within @types

Trying to incorporate certain types from @types/webgl2 into my project has proven to be quite challenging. I diligently followed all the recommendations outlined in this helpful resource: TypeScript typings give me "index.d.ts is not a module" A ...

The state of dynamically created Angular components is not being preserved

My current task involves dynamically creating multiple components to be placed in a table. The code successfully achieves this objective, but the state seems to be getting jumbled up at the level of the dynamically generated components. When a component is ...

Unclear nicknames within the Vite monorepository

An issue has surfaced in the Vite monorepo setup where TypeScript respects @ aliases due to separate tsconfig files (visible in IDE), but Vite does not differentiate them among workspaces during build. The project utilizes Yarn 1.x with workspaces, TypeSc ...

Introducing the 'node' type in tsconfig leads to errors in type definitions

I've encountered an issue with my NodeJS project where I have a type declaration file to add properties to the Request object: @types/express/index.d.ts: import { User } from "../../src/entity/user.entity"; declare global { namespace Exp ...

Implement functionality in Angular to perform tasks when the page is reloaded

I need to perform certain actions in Angular when the page is reloaded, such as adding items to local storage before the page loads and removing items after the page has fully loaded. In other words, I want to execute some tasks both before and after refr ...

Guide to incorporating a Crypto chart widget using Angular 11

In my application, I am looking to add a crypto chart widget for each coin. The inspiration comes from the home page of coinmarketcap.com, but I haven't been able to find any guidance on how to implement it. Currently, I have made some progress, and n ...

Prisma - Modify a single resource with additional criteria

Is it feasible to update a resource under multiple conditions? Consider the tables below: +----------+----------+ | Table1 | Table2 | +----------+----------+ | id | id | | param1T1 | param1T2 | | param2T1 | param2T2 | | idTable2 | ...

Encountering issues while incorporating decimal.js in TypeScript

Incorporating decimal.js into my TypeScript project has proven to be challenging. When attempting to run the code snippet below, I encounter the following error message: Cannot assign to read only property 'constructor' of object '[object Ob ...

In order for Angular jQuery click events to properly function, they must be triggered by a

My admin panel is built using jQuery and Bootstrap, and it functions properly when used outside of the Angular framework. However, after integrating jQuery and Bootstrap into an Angular project and configuring them, I noticed that I had to double click on ...

Do not directly change a prop's value as it will be replaced when the parent component re-renders. Use v-form instead

I'm currently in the process of developing an app using nuxt along with vuetify 2.x, and I keep encountering a specific error message: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Inste ...

Issue with Firebase Functions trigger not activating

Just delving into the world of Firebase Functions for the first time using Typescript. I've written two functions: export const helloWorld = functions.https.onRequest((request, response) => { response.send("Hello from Firebase!"); const testRe ...

Definition of Promise resolve type in Visual Code's d.ts file

Need help with: // api.js export function getLayout(){ return axios.get('/api/layout').then(res => res.data) } // api.d.ts declare interface JSONResponse { meta: object, data: Array<Field> } export declare function getLayout ...

A similar functionality to the async pipe in TypeScript

In my Ionic2 project, I'm utilizing ng-translate from ng2-translate to translate strings in the code. Currently, I am using the service in the following way: translate.get('ERROR').subscribe((res: string) => { //The translated string ...

I'm having trouble grasping the concept of 'globals' in TypeScript/NodeJS and distinguishing their differences. Can someone explain it to me?

As I review this code snippet: import { MongoMemoryServer } from "mongodb-memory-server"; import mongoose from "mongoose"; import request from "supertest"; import { app } from "../app"; declare global { function s ...

The functionality of two-way data binding seems to be failing in Angular 2

I encountered an issue in my Angular 2 application where I attempted to bind view data using ngModel, but it did not function as expected. event.component.html <div class="form-group"> <label for="comment">About Us:</label> ...

The variable "this.data" in Angular 2 is experiencing the issue

I am attempting to access and read the information stored in my JSON file using my "GetJsonService". app.component.ts: data: any; constructor(private jsonService: GetJsonService) {} ngOnInit() { this.getRecords(); console.log(this.data); } get ...

The attribute 'tableName' is not found within the 'Model' type

Currently in the process of converting a JavaScript code to TypeScript. Previously, I had a class that was functioning correctly in JS class Model { constructor(input, alias) { this.tableName = input; this.alias = alias; } } Howev ...

Having trouble capturing emitted events from a child component in Angular 2+?

I have a question as a beginner. I'm trying to send a message from the child component to the parent component but for some reason, it's not working. app.component.html <app-cart-component> [items]="rootItems" (outputItems)=&quo ...

What is the correct way to utilize Global Variables in programming?

Having trouble incrementing the current page in my pagination script to call the next page via AJAX... In my TypeScript file, I declare a global variable like this; declare var getCurrentPage: number; Later in the same file, I set the value for getCurren ...