What is the best way to utilize the "contains" method to find an exact string

I am having trouble matching an exact string using the code snippet below. Instead of returning only elements that match the exact string, it is returning all elements with the same substring.

cy.contains('span', 'Apple');

I also attempted to use regex without success:

cy.contains('span', new Regex("^" + "Apple" + "$"))

If anyone can provide assistance with this issue, I would greatly appreciate it. Thank you!

Answer №1

Your regular expression code is accurate, but there is a mistake in the class name.

It should actually be RegExp.

cy.contains('span', new RegExp("^" + "Apple" + "$"))
  .should('have.text', 'Apple')

This test passes on basic HTML structure:

<span>Apple</span>
<span>Apple1</span>
<span>2Apple</span>

However, keep in mind that contains() only returns the first match. If you need to assert the number of matches, consider using .filter() instead.

cy.get('span')
  .filter((i,el) => el.innerText === 'Apple')
  .should('have.length', 1)

Answer №2

If you're looking to test for a specific text like "Apple," you can try the following code snippet:

cy.contains("span", new RegExp("^Apple$", "g"));

The second argument of the Regexp function is the global flag, but feel free to customize it according to your requirements.

Afterwards, you can create a test using the same approach:

cy.contains("span", new RegExp("^Apple$", "g")).should("have.length", 1)

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

Insert Angular HTML tag into TypeScript

I am currently working on creating my own text editor, but I'm facing an issue. When I apply the bold style, all of the text becomes bold. How can I make it so that only the text I select becomes bold without affecting the rest of the text? Additional ...

What is the process for upgrading TypeScript to the newest version using npm?

My current TypeScript version on my machine is 1.0.3.0 and I am looking to upgrade it to the latest version, which is 2.0. Could someone please guide me on how to accomplish this using npm? ...

What are the steps for importing KnockOut 4 in TypeScript?

It appears straightforward since the same code functions well in a simple JS file and provides autocompletion for the ko variable's members. Here is the TypeScript code snippet: // both of the following import lines result in: `ko` undefined // impo ...

Converting TypeScript into a single line of PHP code

Currently, I am in the process of translating a TypeScript code snippet to PHP, and things are progressing well so far. However, I have come across some one-liners in TypeScript that I am having trouble translating accurately. Here is the TypeScript code ...

Error occurs when Component is used in ngFor

Attempting to implement a component in ngFor as suggested in this Stack Overflow thread results in an error message (Expression has changed after it was checked. Previous value: 'undefined'. Current value: 'false'.). The error occurs w ...

Utilize decorators to access function parameters

Recently, I delved into the realm of creating decorators and learning how to implement them effectively. One question that came up was whether it's possible to access the arguments of a method within the decorator function. For instance, I'm int ...

A guide on harnessing the power of a promise in Typescript

Although I am familiar with async/await/then, I recently stumbled upon something new that sparked my curiosity: Consider the following function: HelloWorld():Promise<string> { return new Promise(resolve => { setTimeout(() => { ...

Pay attention to modifications in a property within an object in the React environment

Below is a React Context Provider containing a simple Counter class with methods stored in the context. import { createContext, useContext } from "react"; class Counter { public count: number = 0; getCount = () => { return this.count ...

Is there a more productive approach to creating numerous React components?

I am currently working on a page where I need to render 8 components. The only thing that differs between each component is the values that are being iterated... <Item classModifier="step" image={Step1} heading={Copy.one.heading} /> <Item ...

Getting Data Beyond the .subscribe() in AngularFire 2

Currently, I have a piece of code that retrieves user data from a database. import { Component } from '@angular/core'; import { NavController } from 'ionic-angular'; import {AngularFireAuth} from 'angularfire2/auth'; import { ...

Having trouble handling responses in nodejs when using inversifyjs

Currently, I am utilizing nodejs alongside typescript, typeorm, and inversify for managing dependency injection. I am also using inversify express utils to handle controllers. However, I am facing an issue where sending a response inside the then or catch ...

How can I properly customize and expand upon a Material UI ListItem component?

I'm currently working with TypeScript version 3.4.5 and Material UI version 4.2. I have the following code snippet: interface MyItemProps { name: string; value: string; } function Item({ name, value, ...props }: ListItemProps<'li&apo ...

Suggestions for developing a component library for angular/react modules

I'm currently leading an initiative at my workplace to implement the use of standardized components across all our projects in order to maintain a consistent look and functionality that aligns with our brand. My main concern is figuring out how to eff ...

Angular 2 - Can a Content Management System Automate Single Page Application Routing?

I am interested in creating a single-page application with an integrated content management system that allows users to edit all aspects of the site and add new pages. However, I have found it challenging to configure the SPA to automatically route to a n ...

Using prevState in setState is not allowed by TypeScript

Currently, I am tackling the complexities of learning TypeScipt and have hit a roadblock where TS is preventing me from progressing further. To give some context, I have defined my interfaces as follows: export interface Test { id: number; date: Date; ...

Encountering a problem when attempting to add ngrx to an Angular project

I'm currently in the process of setting up ngrx in my Angular application. After running the command ng add @ngrx/store@latest An error occurred with the following details: npm resolution error report 2022-07-07T20:36:16.089Z While resolving: [em ...

Learn the proper way to write onClick in tsx with Vue 2.7.13

current version of vue is 2.7.13 Although it supports jsx, I encounter a type error when using onClick event handling. The type '(event: MouseEvent) => Promise<void>' cannot be assigned to type 'MouseEvent' Is there a correct ...

Upon selecting an option in the mat-select element, the form does not update its pristine state to

I recently encountered an issue with my Angular Material mat-select form. I am populating the options from an observable and setting the selected item value programmatically, which is working fine. However, I faced a problem where I expected changing the m ...

Mastering the Art of HTML Binding in Angular 8

I am facing a challenge in Angular 8 with displaying HTML content. The app I'm building in Angular 8 has a Flask backend that sends JSON data containing an HTML template to the frontend. My goal is to render this template in Angular. Here is the JSON ...

What are the steps to enable readonly or disabled functionality in Ionic 2?

Trying to make a field readonly or disabled in an ionic2 form: <ion-item> <ion-label fixed>Category <ion-icon name="ios-arrow-forward"></ion-icon></ion-label> <ion-input type="text" [disabled]="false" id="category_ ...