Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
983 views
in Technique[技术] by (71.8m points)

Unable to use minimatch with intercept in Cypress 6.2.1

I have an issue with cy.intercept that I can't seem to figure out how to solve, in our project we used to use route, but now trying to start using intercept. So, our rotes used to be defined like this:

'upload: {route: `api/cases/import-data/**`, alias:'upload'}

So we used minimatch's ** to mach anything after the import-data/, and that is currently not working with intercept.

So I'm trying to use RegExp instead now, so my question is pretty simple, what should I replace ** with in a RegExp? Nothing seems to be working and I'm getting a timeout error.

My function:

function listener({ route, method = 'POST', onRes = () => { }, alias = 'listener' }) {
  const url = new RegExp(`${Cypress.config().beUrl}${route}`);

  cy.intercept(
    method,
    url,
    (req) => {
      req.reply(res => {
        onRes(res);
      });
    }
  ).as(alias);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

With regex you don't need anything to replace minimatch '**'. "api/cases/import-data/**" can translate to /api/cases/import-data/.

But note the escaped forward slashes, which I think is the missing ingredient in

const url = new RegExp(`${Cypress.config().beUrl}${route}`)

The strings you use to build the regex don't contain the backslash escape for path delimiters.

This might work

const escapedBaseUrl = Cypress.config().beUrl.replace('/', '/');
const escapedRoute = route.replace('/', '/');
const url = new RegExp(`${escapedBaseUrl}${escapedRoute}`);

but sooner or later you can run into other characters that need escaping, so you can use a package like regex-escape,

const RegexEscape = require("regex-escape");
...
const url = new RegExp(RegexEscape(`${Cypress.config().beUrl}${route}`));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...