What is the best approach for intercepting and matching multiple paths in Cypress?

Picture a scenario where you are on a webpage that lets you choose a vehicle such as a car, truck, or bike. After making your selection, you can save it by clicking a Save button. Depending on the type of vehicle chosen, the Save button will trigger an appropriate API call like POST /Inventory/AddCar, /Inventory/AddTruck, /Inventory/AddBike. In Cypress, I aim to intercept these calls once the Save button is clicked and then wait for them to complete. Despite trying to use regex in my interception method as shown below, I ran into issues. How can I effectively intercept multiple similar API calls?

// A function within the (web) page object.
function saveVehicle()
{
  const regex = `/[\/Inventory\/AddCar]|[\/Inventory\/AddTruck]|[\/Inventory\/AddBike]/`
  cy.intercept("POST", regex).as("saveVehicle");
  saveButton.click().wait("@saveVehicle");
}

Answer №1

In the context of square brackets, they represent a single character from those inside them, not the entire string.

If you prefer, you can use parentheses instead (for a matching group) or omit them altogether.

When applying the regex directly, there is no need to use string delimiters; the forward slash (/) delimiters will suffice.

const pattern = /(\/Inventory\/AddCar)|(\/Inventory\/AddTruck)|(\/Inventory\/AddBike)/
cy.intercept('POST', pattern).as('saveVehicle')

Test your regex skills here.

Answer №2

Using a regex is recommended, but using javascript within a routeHandler might be more straightforward.

cy.intercept("POST", '/Inventory/*', (req) => {
  if (req.url.includes('AddCar') || req.url.includes('AddTruck') || req.url.includes('AddBike')) {
    req.alias = 'saveVehicle'
  }
})

saveButton.click()
cy.wait("@saveVehicle")

Furthermore, as mentioned in the documentation,

It is not safe to continue chaining commands after calling .click()

It is uncertain if this applies in this scenario, but it is always best to follow secure coding practices.

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

Changing URL Links to Plain Text with Regular Expressions

When sending an email from my application, I am primarily using HTML format and applying a regex to remove the HTML tags for a plain-text alternative view. (using @"<(.|\n)*?>"). My goal is to substitute the <a> hyperlink tag with a plain- ...

Proper method for a service to invoke a member function of a Component in Angular 2

What is the best way to call a service method from a component in Angular2 with TypeScript? My service needs to periodically notify components of certain events. Is there a more efficient approach than keeping a reference to the component in the service a ...

Make Ionic 2 Navbar exclusively utilize setRoot() instead of pop()

When navigating to a different page, the ion-navbar component automatically includes a back button that uses the pop() method to return to the previous page. Is there a way to modify this behavior so that it utilizes the setRoot() method instead of pop(), ...

A union type that includes integers and NaN as valid return values

I have a function for comparison that has a union return type. It can return -1, 1, or 0. However, I need to handle a special case when at least one of the items being compared is not defined. While the compiler allows me to include null as a potential ret ...

What is causing the undefined value for the http used in this function?

My Code Component import { Component, OnInit } from '@angular/core'; import { Http } from '@angular/http'; @Component({ selector: 'app-root', template: '<button id="testBtn"></button>' }) export c ...

Transforming the timestamp to a date object using Angular and Typescript

As a newcomer to Angular 2.0, I've been delving into new concepts in order to grasp it better. However, despite encountering this common issue multiple times and reading through various solutions, I haven't been able to find the answer to my prob ...

What is the best method for translating object key names into clearer and easier to understand labels?

My backend server is sending back data in this format: { firstName: "Joe", lastName: "Smith", phoneNum: "212-222-2222" } I'm looking to display this information in the frontend (using Angular 2+) with *ngFor, but I want to customize the key ...

Using TypeScript with CanvasJS

While working on my TypeScript project, I encountered an issue with integrating CanvasJS using the declaration file - index.d.ts. The corresponding JavaScript file can be found at . I am utilizing require.js in my project, but it crashes when running beca ...

Is it advisable to standardize the state within an Angular application?

Currently, our team is delving into our inaugural Angular projects with ngrx-store. We find ourselves deliberating whether the state should be normalized or not, sparking varying viewpoints. Proponents of a nested store argue that it would streamline main ...

Encountering issues with integrating interactjs 1.7.2 into Angular 8 renderings

Currently facing challenges with importing interactive.js 1.7.2 in Angular 8. I attempted the following installation: npm install interactjs@next I tried various ways to import it, but none seemed to work: import * as interact from 'interactjs'; ...

Error: Headers already sent to the client, cannot set new headers

I am currently working on creating a basic API using passport-jwt and passport-local-mongoose. I have successfully set up all the JWT functions and created routes for registering and signing in users. One of these routes is meant to handle a GET request in ...

TypeScript sometimes struggles to accurately deduce the precise return type of a function

I have a function called myCallback const myCallback = (param: number) => { // doSomething }; Now, I want to create another function, useMyCallback, that may or may not receive a parameter and will return myCallback either bound or unmodified: const ...

The "main" entry for ts-node is not valid when running ts-node-dev

Recently, I embarked on a TypeScript project using yarn where I executed the following commands: yarn init -y yarn add typescript -D yarn tsc --init yarn add ts-node-dev -D Subsequently, I crafted a script titled dev that triggers tsnd src/index.ts, howev ...

Typescript - Identifying child type based on the specified property in keyof

I'm exploring the possibility of enhancing an interface by adding extra options to it. For example: interface IRole { id: number; name: string; } interface IAddress { line1: string; line2: string; city: string; state: string; zip: strin ...

Tips for incorporating classes as a prop in material ui components

When working with material ui, I often find myself creating generic components where the styling is actually defined in a parent or grandparent component. For example: const GenericDescendant = (props: DescendantProps) => { const { classesFromAncestor ...

Does the onAuthStateChanged listener in firebase trigger immediately upon user login or logout?

//initialize auth change listener useEffect(() => { auth.onAuthStateChanged((user) => { if (user) { router.replace('/') } }) setInitializing(false) }, []) //*handled by login button const login = asy ...

Tips for refreshing a component after fetching a new page using the useQuery function

Attempting to retrieve and display data from my custom API using axios and react-query's useQuery. The API incorporates pagination, and I have implemented a table with an option to select the page that displays the current data. Everything functions c ...

Could someone provide a detailed explanation of exhaustMap in the context of Angular using rxjs?

import { HttpHandler, HttpInterceptor, HttpParams, HttpRequest, } from '@angular/common/http'; import { Injectable } from '@core/services/auth.service'; import { exhaustMap, take } from 'rxjs/operators'; import { Authe ...

Leveraging CSS attribute selectors within JSX using TypeScript

With pure HTML/CSS, I can achieve the following: <div color="red"> red </div> <div color="yellow"> yellow </div> div[color="red"] { color: red; } div[color="yellow"] { color: yellow; ...

What is the best way to restrict a mapped type in typescript to only allow string keys?

In the Typescript documentation, I learned about creating a mapped type to restrict keys to those of a specific type: type OptionsFlags<Type> = { [K in keyof Type]: boolean; }; If I want to use a generic type that only accepts strings as values: t ...