1

I am testing search functionality in one of my Cypress tests and having trouble getting to all parts of the request url. On my page, I have a form that a user can enter a number to search for. When a user clicks "Search", the system makes an ajax request with the appropriate data. Everything is working great.

In my Cypress test, I'm intercepting a GET request in one of my tests like this:

cy.intercept('GET', '/api/v1/foo/?include=**').as('myRequest');

...

That is the GET request that is made when a user clicks the submit button to search.

Within my test, I am entering text into a text field like this:

...

cy.get('[data-cy="number"]').type('12345');

The text is getting properly interred into the input. Next, I am triggering an ajax request like this:

...

cy.get('[data-cy="search"]').should('exist').click();

cy.wait('@myRequest').then((interception) => {
    console.log(interception.request.url); // /api/v1/forms/?include=foo <-- does not have filter[number]...
    expect(interception.request.url).to
    .include('filter[number]=12345');
});

When submitting a real request (not through cypress) the request url looks like this:

https://example.com/api/v1/foo/?include=bar&filter[number]=12345

However, when cypress makes the request, it's seemingly not picking up the query field and my test is failing.

I've also tried using expect(interception.request.query) but it is always undefined.

How can I properly pick up the filter[number] query param in my test?

Fody
  • 23,754
  • 3
  • 20
  • 37
Damon
  • 4,151
  • 13
  • 52
  • 108
  • Maybe the endpoint is not triggered with the typed value. May be you can try this `cy.get('[data-cy="number"]').type('12345').trigger('input')` and then intercept. – Alapan Das Jun 21 '22 at 14:37
  • Hmmm. No luck. When I look at the network tab, I can see the query param getting added. I just seems isolated to Cypress that it can't "pick it up". – Damon Jun 21 '22 at 15:14
  • Another option would be to play around with the URL in `cy.intercept` if that helps. – Alapan Das Jun 21 '22 at 15:18

1 Answers1

0

It looks like there's preceding requests that are using up your cy.wait('@myRequest').

Query parameter matching is a bit tricky, but it works using a routeMatcher function and checking for the correct params, then assigning a dynamic alias.

cy.intercept('/api/v1/foo/?include=**', (req) => {
  if (req.query.include === 'bar' && req.query["filter[number]"] === '12345') {
    req.alias = 'myRequest'   // alias for only these parameters
  }
  req.continue()
})

cy.get('[data-cy="search"]').should('exist').click();

cy.wait('@myRequest').then((interception) => {
  ...

})
Fody
  • 23,754
  • 3
  • 20
  • 37
  • This was exactly the issue I found. There was an `@wait` command that was nested further upstream I didn't catch. Once I moved my following `@wait` further into my test, things worked as needed. Thank you so much for your time! – Damon Jun 22 '22 at 12:23