24

I am stubbing an api request in my end-to-end test and would like to be able to return a different response depending on the request parameters that are sent out.

Currently, my stub is returning a static response regardless of what is posted, and looks like this:

cy.server()
cy.route({
    method: 'POST',
    url: '**/redeem-code',
    status: 200,
    response: {
        status: "Success"
    },
    delay: 500
})

I would like to be able to check the posted request parameters and then conditionally decide which response to return. I'm trying to do something like this:

cy.server()
cy.route({
    method: 'POST',
    url: '**/redeem-code',
    status: 200,
    response: (req) => {
        if(req.code == '1234') return { status: "Success" }
        else return { status: "Failure" }
    },
    delay: 500
})

Obviously, the code above doesn't work; it's just an example of what I'm trying to do.

I know Cypress allows for response methods, but I can't find the syntax for what I'm wanting to do anywhere in their docs. How do I get the request parameters in my response method so I can decide which response to return?

EmacsVI
  • 531
  • 1
  • 5
  • 15

3 Answers3

6

This is sadly currently not supported with cy.server.

The issue is being tracked here : https://github.com/cypress-io/cypress/issues/521

Workaround

Use standard javascript mocking. You can run this mocks in tests by using cypress onBeforeLoad, mentioned a few times in the linked issue. Its not pretty. Hopefully cypress gets native support in cy.server.

basarat
  • 207,493
  • 46
  • 386
  • 462
0

I had the same problem and made a feature to enable this. It does require a bounce back url to be stood up but the code install instructions can be seen here https://bitbucket.org/snippets/matt-tasc/onraxo

matthewdaniel
  • 1,572
  • 2
  • 18
  • 32
-1

I believe this should work

cy.server({
        onResponse: ({ status, url, response }) => {
             if(url !== 'yoururl') return response;
             return { 
                ...response,
               body: { status: status === 1234 ? 'success' : 'failure' }
             };
        }    
});
Toli
  • 4,534
  • 5
  • 30
  • 46
  • Thanks for your advice. You were very close, but no cigar. See my updated question for more details. – EmacsVI Sep 11 '18 at 18:29