最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to add regular expression to filter out the xhr URL in Cypress - Stack Overflow

programmeradmin5浏览0评论

I have a scenario where in I have to process and validate the XHR response of nearly equal URLs:

URL-1: http://localhost:8080/api/customer/123/acounts
URL-2: http://localhost:8080/api/customer/asfgeras-qwe2-34hg-qwerhngfa

when I initialize the server in cypress and mention the xhr url as following, it always returns me the response of the URL-1 (which in my case is called first by the AUT) but I am unable to fetch the response of URL-2 although it is called in the AUT.

cy.server();
cy.route('GET','**/api/customer/**').as('GETCustomer);

I want to capture the response of URL-2. Please suggest any approach to do so (preferably regEx)

I have a scenario where in I have to process and validate the XHR response of nearly equal URLs:

URL-1: http://localhost:8080/api/customer/123/acounts
URL-2: http://localhost:8080/api/customer/asfgeras-qwe2-34hg-qwerhngfa

when I initialize the server in cypress and mention the xhr url as following, it always returns me the response of the URL-1 (which in my case is called first by the AUT) but I am unable to fetch the response of URL-2 although it is called in the AUT.

cy.server();
cy.route('GET','**/api/customer/**').as('GETCustomer);

I want to capture the response of URL-2. Please suggest any approach to do so (preferably regEx)

Share Improve this question edited Nov 11, 2020 at 15:24 James Z 12.3k10 gold badges27 silver badges47 bronze badges asked Nov 11, 2020 at 13:47 NavaneethNavaneeth 711 silver badge5 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 2

The above solution works for a wild card search criteria but not for specific api search. Using something like this can help you sort out the request

cy.route('GET', /\/api\/customer\/([a-zA-Z0-9]){8}-([a-zA-Z0-9]){4}-([a-zA-Z0-9]){4}-([a-zA-Z0-9]){4}-([a-zA-Z0-9]){1,}$/).as('GETCustomer');

Cypress uses minimatch to filter URLs. Accordingly, you need to specify **/customer/*.

  • ** — feature known as globstar. Matches all files and zero or more directories and subdirectories. If followed by a /it matches only directories and subdirectories. To work that way it must be the only thing inside the path part e.g. /myapp/**.js will not work that way.
  • * — Matches any string.
Source: https://globster.xyz/.

Full code:

cy.server();
cy.route('GET','**/api/customer/*').as('GETCustomer);
...
cy.wait('@GETCustomer')
  .then((response) => {
     <your handler here>
   });

Check online here

cy.server() and cy.route() are deprecated, see link

Use cy.intercept() instead, info here

Example:

cy.intercept('GET', /api\/node1\/node2\/data$/).as('myAlias');

The second parameter above it's a random REGEX, but you can also pass a STRING.

then in order to wait for the async call you have to write:

cy.wait('@myAlias')
发布评论

评论列表(0)

  1. 暂无评论