0

我已经阅读了 Cypress 上v6.9.1关于拦截的文档,但我在真正理解如何匹配单个单词 url 时遇到了一些困难。

我面临的问题的一个实际例子。我提出以下请求以label在我的应用程序中创建一个:

POST http://localhost:8081/70e70322-1633-4ca9-b1e2-9240cef416e7/label

我会假设,从文档中我可以通过执行以下操作来匹配这条路线:

// My code
cy.intercept("POST", "/label").as("createLabel");

// From the examples in Cypress pages
cy.intercept('GET', '/users')
// matches this: GET http://localhost/users
// ...but not this: POST http://localhost/users

我尝试了以下方法:

// Passing a simple string
cy.intercept("POST", "label").as("createLabel");

// Passing a regex
cy.intercept("POST", /label/g).as("createLabel");

// Passing a glob pattern
cy.intercept("POST", "**/label").as("createLabel");

我对此一头雾水,并没有真正理解拦截基于单个单词的请求的确切方法。这是一个简单的例子,但我在许多其他测试中都遇到了这个问题,为了解决我的问题,我必须拦截所有请求(这使我的测试变得脆弱,而且没有未来的证明):

// This is just a "hacky" way to make it work and avoid the app to 
// make a request to my backend after creating another resource
cy.intercept("GET", "*");

问题

如何使赛普拉斯匹配请求中的单个单词?

  • GET http://localhost/label-> 请拦截labelURL 上的请求
  • POST http://localhost/user/{userId}/comment-> 请拦截user对他们的请求
  • POST http://localhost/user/{userId}/comment-> 请拦截comment对他们的请求
4

2 回答 2

2

在@Sebastiano 的帮助下,我使用了 minimatch并发现当我不添加不匹配的选项时。

一个例子:

// doesnt match
cy.intercept("POST", "**/label").as("createLabel");

// it maches
cy.intercept("POST", "**/label", { statusCode: 200 }).as("createLabel");
于 2022-01-04T19:08:55.510 回答
0
/// <reference types="cypress" />

describe('cy.intercept', () => {

    it('http://localhost/label', () => {
        cy.intercept('**/label').as('alias1');
    });

    it('http://localhost/user/{userId}/comment', () => {
        cy.intercept({
            method: 'POST',
            url: '**/user/*',
        }).as('alias2');
    });

    it('http://localhost/user/{userId}/comment', () => {
        cy.intercept({
            method: 'POST',
            url: '**/comment',
        }).as('alias3');
    });


    it('other try', () => {
        cy.intercept({
            method: 'POST',
            hostname: 'localhost',
            path: '**/comment', //pathname: will also work
        }).as('alias4');
    });
});

alias1没有花括号,因为 GET 是默认方法。

主机名- 表示 api 主机名部分 ( https://example.com )

url - 表示带有端点和查询的整个 api 地址(在这些情况下没有查询)

path - 主机名后的 HTTP 路径,带有查询

路径名- 类似路径,但没有查询

在这里阅读:https ://docs.cypress.io/api/commands/intercept 。

于 2022-01-04T00:49:46.320 回答