0

I mocking endpoint with query parameters in Cypress. But when give query field with array of field items.

 cy.intercept(
    {
      method: 'POST',
      pathname: '/api/initiate/manual',
      hostname: Cypress.env('CY_API_URL'),
      https: true,
      query: {
        orderId: '13535353453',
        items: [
          {
            id: '3853438474',
            name: 'Standard Wholesale HB Yellow Pencils',
          },
          {
            id: '2424534353453',
            name: 'natural wood dipped end 72 color',
          },
        ],
      },
    },
    {
      statusCode: 200,
    },
  ).as('mockManuelOrder');

it gives error :

CypressError

An invalid RouteMatcher was supplied to cy.intercept(). query.items must be a string or a regular expression.

how I can solve the problem ?, I need to send the query parameters as it is.

2 Answers 2

1

It should be working:

query: JSON.stringify({
    orderId: '13535353453',
    items: [
      {
        id: '3853438474',
        name: 'Standard Wholesale HB Yellow Pencils',
      },
      {
        id: '2424534353453',
        name: 'natural wood dipped end 72 color',
      },
    ],
  }),
Sign up to request clarification or add additional context in comments.

2 Comments

According to the docs, query should be an object.
req.query record is released from 7.6.0 of cypress
1

This seems to work, although I've guessed what the URL looks like when sent over the wire (may not correspond).

Basically, I've moved the query params from the RouteMatcher into the RouteHandler and used javascript to check them.

If they match, I assign a dynamic alias and send the stub response.

cy.intercept(
{
  method: 'POST',
  pathname: '/api/initiate/manual',
  hostname: Cypress.env('CY_API_URL'),
  https: true,
},
(req) => {
  const params  = {
    "orderId": "13535353453",
    "items": [
      {"id": "3853438474", "name": "Standard Wholesale HB Yellow Pencils"},
      {"id": "2424534353453", "name": "natural wood dipped end 72 color"}
    ]
  }

  const matches = req.query.orderId === params.orderId &&
      req.query.items == JSON.stringify(params.items)

  if (matches) {
    req.alias = 'mockManuelOrder'
    req.reply({statusCode: 200})
  }
}

// trigger POST

cy.wait('@mockManuelOrder')    // passes

2 Comments

Yeah, can be tricky to make a match. Can you please show how the request call you are trying to catch looks in the network tab?
I'm thinking to drop the query parameters from the matching part and filter them in the RouteHandler using javascript. You can assign the alias dynamically (ie. only when the query is the required one).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.