javascript Cypress Intercept,正在优化url

tvokkenx  于 2023-05-21  发布在  Java
关注(0)|答案(2)|浏览(114)

我正在拦截赛普拉斯的一个请求,我试图不硬编码的东西。为了使它正确工作,我必须添加一个“1”,因为我试图拦截这样的东西:

/api/v1/contacts/cfs:12345/forms/144543

问题是,如果我使用表单/**,还有其他像/forms/something这样的请求会被拦截,导致以下情况:

let urlResponse = '/api/v1/contacts/cfs:' + $code + '/forms/1**'

有没有正则表达式或者其他什么东西可以让我拦截forms/number而不是forms/somethingforms/number/something的URL?

blmhpbnm

blmhpbnm1#

下面是一些正则表达式,用于匹配.../forms/number模式。

const inputs = [
  '/api/v1/contacts/cfs:12345/forms/144543',
  '/api/v1/contacts/cfs:12345/forms/something',
  '/api/v1/contacts/cfs:12345/forms/144543/something'
];

const regex = new RegExp('/api/v1/contacts/cfs:12345/forms/[0-9]+$');

for (let input of inputs) {
  const isMatch = regex.test(input);
  console.log(isMatch);
}
7y4bm7vi

7y4bm7vi2#

Cypress使用minimatch来验证URL,因此您可以用途:

const part = '12345';
cy.intercept(`/api/v1/contacts/cfs:${part}/forms/1[0-9]*`).as('alias');

并检查它是否实际上与预期的匹配:

expect(Cypress.minimatch('/api/v1/contacts/cfs:12345/forms/144543', `/api/v1/contacts/cfs:${part}/forms/1[0-9]*`)).to.be.true;
expect(Cypress.minimatch('/api/v1/contacts/cfs:12345/forms/something', `/api/v1/contacts/cfs:${part}/forms/1[0-9]*`)).to.be.false;
expect(Cypress.minimatch('/api/v1/contacts/cfs:12345/forms/144543/something', `/api/v1/contacts/cfs:${part}/forms/1[0-9]*`)).to.be.false;

相关问题