如何添加正则表达式来过滤Cypress中的xhr URL



我有一个场景,在该场景中,我必须处理和验证几乎相等URL的XHR响应:

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

当我在柏树中初始化服务器并提到xhr url时,它总是向我返回url-1的响应(在我的情况下,它首先由AUT调用(,但我无法获取url-2的响应,尽管它是在AUT中调用的。

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

我想捕捉URL-2的响应。请建议任何方法(最好是regEx(

Cypress使用minimatch来过滤URL。因此,您需要指定**/customer/*

  • **——被称为globstar的特征。匹配所有文件和零或更多的目录和子目录。如果后面跟a/it匹配只有目录和子目录。要以这种方式工作,必须路径部分中唯一的东西(例如/myapp/**.js(不会起作用方式
  • *—匹配任何字符串
来源:https://globster.xyz/.

完整代码:

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

在线查看此处

上述解决方案适用于通配符搜索条件,但不适用于特定的api搜索。使用这样的东西可以帮助你整理请求

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');

cy.server((和cy.route((已弃用,请参阅链接

改为使用cy.entercept((,此处为信息

示例:

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

上面的第二个参数是随机REGEX,但也可以传递STRING。

然后为了等待异步调用,你必须写:

cy.wait('@myAlias')

最新更新