Consider the below code to intercept an API call. It checks if query parameter cliendId = 36
. I want to make this code only consider the query param clientId
and NOT its value of 36. So, I tried to use "*" instead of '36' and it did not work. I could not find the answer in existing stack overflow questions. How do I make cypress only intercept based on the query param name and not its value ?
cy
.intercept({
pathname: '/api/program/v1/program'
query: {
clientId: '36'
}
})
.as('createProgram');
You can use path
instead of pathname
, then include the query in the pathname string with a wildcard.
When fetching first client 36 then client 48, I wait on each one and verify it's clientId
, using the same cy.intercept()
:
cy.intercept({ path: '/todos/1?clientId=*' }).as('client')
...
cy.wait('@client').its('request.query').should('have.property', 'clientId', '36')
cy.wait('@client').its('request.query').should('have.property', 'clientId', '48')
From RouteMatcher options
Option | Description |
---|---|
path | HTTP request path after the hostname, including query parameters |
pathname | Like path, but without query parameters |
Matching a query key at any position
it('path with wildcard - key in any query position', () => {
cy.intercept({ path: '/todos/1?*clientId=*' }).as('client')
cy.then(() => {
const win = cy.state('window')
const queryString = 'age=22&clientId=48&countryId=22'
win.fetch(`https://jsonplaceholder.typicode.com/todos/1?${queryString}`)
})
cy.wait('@client').its('request.query').should('have.property', 'clientId', '48')
})
Matching two keys out of three in strict order
it('path with regex - matches clientId followed by countryId (in strict order)', () => {
cy.intercept({ path: /\/todos\/1\?(.*clientId=.*)(.*countryId=.*)/ }).as('client')
cy.then(() => {
const win = cy.state('window')
const queryString = 'age=22&clientId=48&countryId=22'
win.fetch(`https://jsonplaceholder.typicode.com/todos/1?${queryString}`)
})
cy.wait('@client').its('request.query')
.should(query => {
expect(query).to.have.property('clientId', '48')
expect(query).to.have.property('countryId', '22')
})
})
Matching two keys out of three in any order
it('path with regex - matches clientId and countryId in any order', () => {
cy.intercept({ path: /\/todos\/1\?(?=.*countryId=.*)(?=.*clientId=.*)/ }).as('client')
// (?=.*key=.*) is positive lookahead that allows key to be in any order
cy.then(() => {
const win = cy.state('window')
const queryString = 'age=22&clientId=48&countryId=22&gender=male'
win.fetch(`https://jsonplaceholder.typicode.com/todos/1?${queryString}`)
})
cy.wait('@client').its('request.query')
.should(query => {
expect(query).to.have.property('clientId', '48')
expect(query).to.have.property('countryId', '22')
})
})
I would encourage hands-on experimentation, as it's a great way to improve skills.