How to use a specific url over a glob in cy.intercept()?

Viewed 36

I have two intercepts:

cy.intercept(
  'GET',
  '**/foo/*',
 {
  fixture: 'foo.json'
 }
)

and

cy.intercept(
  'GET',
  '**/foo/bar',
 {
  fixture: 'bar.json'
 }
)

I always get the response from the first intercept. Changing the order of them in the code doesn't matter. What am I doing wrong?

How do I get a response from a specific url over a glob one?

1 Answers

You can conditionally return different fixtures based on the response, using req.reply()

cy.intercept(
  'GET',
  '**/foo/*',
  (req) => {
    req.reply({
      status: 200,
      fixture: req.url.endsWith('/bar') ? 'bar.json' : 'foo.json'
    });
  });

In the above, we're doing a simple ternary to determine whether to return bar.json or foo.json. If there is more complicated logic, you could extract that part out to a constant above the req.reply().

Related