2

I wish to create a custom command that contains status code assertions:

cy.wait('@interceptedEndpoint')
    .its('response.statusCode')
    .should('eq', 200)

the last two lines are what I want inside the custom command

.its('response.statusCode')
.should('eq', 200)

My initial idea is below which obviously wouldn't work

Cypress.commands.add('checkResponse', {prevSubject: 'element'}, () => {
    .its('response.statusCode')
    .should('eq', 200)
})

What am I missing above to make the custom command creation correct?

EDIT: In addition to Udo.Kier's answer. I needed to set prevSubject to true to make it accept the response for the expected assertion.

KiritoLyn
  • 626
  • 1
  • 10
  • 26

1 Answers1

3

You can try adding the subject parameter,

Cypress.commands.add('checkResponse', {prevSubject: true}, (subject) => {
  cy.wrap(subject)
    .its('response.statusCode')
    .should('eq', 200)
})

...

cy.wait('@interceptedEndpoint').checkResponse()

Alternatively, with the wait inside the custom command:

Cypress.commandsCommands.add('waitAndCheckResponse', (subjectAlias) => {
  cy.wait(subjectAlias)
    .its('response.statusCode')
    .should('eq', 200);
})

...

cy.waitAndCheckResponse('@interceptedEndpoint')
Udo.Kier
  • 228
  • 7
  • How do I use the custom command to chain into a `cy.wait('@anyAlias')`? It seems to not work when I try `cy.wait('@anyAlias').checkResponse()` – KiritoLyn Feb 16 '23 at 20:00
  • I didn't try it, but the `cy.wait('@anyAlias')` is supposed to yield an "interception" object which has `request` and `response` properties so logically this should succeed. – Udo.Kier Feb 16 '23 at 20:03
  • Yes, the `cy.wait('@anyAlias')` came from a `cy.intercept()` command. The error by the way is: `cy.checkResponseStatus() failed because it requires a DOM element. The subject received was Object{10}` – KiritoLyn Feb 16 '23 at 20:11
  • I was able to make it work. You are right about the error part. I changed it to `{prevSubject: true}`. It shouldn't be `'element'` since we are asserting a response from an intercept if I understood it correctly. But your edited answer is also a good option. – KiritoLyn Feb 16 '23 at 20:40
  • 1
    Ok, I missed that variation. If the `prevSubject` is removed altogether the yielded value is blocked from entering the custom command. – Udo.Kier Feb 16 '23 at 21:24
  • Is your second answer final? I'm not familiar with `cy.wrapwait()` – KiritoLyn Feb 17 '23 at 05:54
  • No, that's a mistake - thanks for pointing it out – Udo.Kier Feb 17 '23 at 19:25