Cypress not matching routes

与世无争的帅哥 提交于 2020-01-04 05:51:06

问题


I am trying to write a cypress test that emulates a slow API, so after reading some documentation I came up with this:

before(function() {
    cy.server({delay: 5000});
});

beforeEach(() => {
    cy.route({
        method: "GET",
        url: "**/api/**"
    });
    cy.visit("http://localhost:9000");
});

That should add a 5 second delay to all requests to API, right?

The issue I am seeing is that it is not matching to any requests even through there are plenty of calls to */api/*. The cypress GUI does however see the route... it is just not matching.

What could be the cause of this?


回答1:


If you put in the entire route, as it appears in the cypress log, you will probably find that it works.

It seems like the look-ahead globbing isn't implemented very well by minimatch. It delimits fine on the / char but not so well on ? or #, so if you're trying to accommodate query strings, this is probably where you're coming unstuck.

You can use Cypress.minimatch in the console to see what's going on. More info on how to do this in the docs.

Cypress will also accept regexes. Something like /\/api\// should work for you.




回答2:


I am assuming your matcher is not working and your request does not say (XHR STUB)

If you are using the GUI, you should see a request that will look like this

(XHR) GET 200 /YOUR_API/YOUR_ROUTE

copy that (/YOUR_API/YOUR_ROUTE) and it should match

if should say (XHR STUB) after you stub it




回答3:


Are you making a direct XHR request, or are you using fetch? Cypress network stubbing/mocking only works with actual XHR requests (fetch is its own type of request).

There's an open issue (3+ years old) about this, and buried in there is a great link to some solutions, including this one below, which works brilliantly.

EDIT: Alternatively, you could use axios for your HTTP requests, which sends actual XHR requests instead of fetch requests, so no Cypress config is needed. I think the resulting code is cleaner as well.

  let polyfill;

  // grab fetch polyfill from remote URL, could be also from a local package
  before(() => {
    const polyfillUrl = 'https://unpkg.com/unfetch/dist/unfetch.umd.js'
    cy.request(polyfillUrl)
      .then((response) => {
        polyfill = response.body
      })
  })

  beforeEach(() => {
    cy.visit('/', {
      onBeforeLoad (win) {
        delete win.fetch
        // since the application code does not ship with a polyfill
        // load a polyfilled "fetch" from the test
        win.eval(polyfill)
        win.fetch = win.unfetch
      },
    })
  });


来源:https://stackoverflow.com/questions/54148449/cypress-not-matching-routes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!