【发布时间】:2021-12-31 14:02:24
【问题描述】:
我已经阅读了 Cypress v6.9.1 上关于 intercept 的文档,但我在真正理解如何匹配单个单词 url 时遇到了一些困难。
我面临的问题的一个实际示例。我提出以下请求以在我的应用中创建 label:
POST http://localhost:8081/70e70322-1633-4ca9-b1e2-9240cef416e7/label
我会假设,从docs,我可以通过这样做来匹配这条路线:
// 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", "*");
问题
如何让 Cypress 匹配请求中的单个单词?
-
GET http://localhost/label-> 请拦截 URL 上有label的请求 -
POST http://localhost/user/{userId}/comment-> 请拦截带有user的请求 -
POST http://localhost/user/{userId}/comment-> 请拦截带有comment的请求
【问题讨论】:
-
你检查了 cy.intercept('GET', '**/label') 并且它不适合你吗?也许您可以使用 Cypress.minimatch 更轻松地找到合适的模式 --> docs.cypress.io/api/utilities/minimatch
-
@SebastianoVierk 对测试非常有用。我也尝试了您的解决方案,但不匹配。我并没有完全找到问题所在,而是采用了与
cy.intercept("GET", "label?page=1")匹配更受限制的方式的解决方案。这似乎解决了我现在的问题。如果找到答案,我会写下这个问题的答案
标签: cypress cypress-testing-library