简体   繁体   中英

Stub the same endpoint twice in cypress

I want to stub the same API endpoint twice, so the second call returns different response than the first one. Here is snippet how I imagine this would work:

cy.route('POST', 'access-tokens', '@loginFailResponse', {status: 401}).as('loginFail')
cy.route('POST', 'access-tokens', '@loginSuccessResponse').as('loginSuccess')

The first time I try to login it denies access, I change form inputs and then it should let me in.

I tried to wrap second cy.route(...) definition as callback function to first output but cypress denies calling cy.anything in promises. Like in example below

cy.route('POST', 'access-tokens', '@loginFailResponse', {status: 401, onResponse: () => {
      cy.fixture('login_screen/login_success_response.json').as('loginSuccessResponse')
      cy.route('POST', 'access-tokens', '@loginSuccessResponse').as('loginSuccess')}
}}).as('loginFail')

here is my test case:

cy.route('POST', 'access-tokens', '@loginFailResponse', {status: 401}).as('loginFail')
cy.route('POST', 'access-tokens', '@loginSuccessResponse').as('loginSuccess')
cy.get("form input[type='email']").type("bad@email.com")
cy.get("form input[type='password']").type("Bad password")
// this should fail
cy.get("form").submit()
cy.get("form input[type='password']").type("g00d@password.com")
// this should let me in
cy.get("form").submit()

Everytime you define .route('VERB', '/endpoint', ...) it overrides your previous definition. The simplest solution would be to override this endpoint after you finish your first call

This test will work for you, Filip.

cy.route('POST', 'access-tokens', '@loginFailResponse', {status: 401}).as('loginFail')
cy.get("form input[type='email']").type("bad@email.com")
cy.get("form input[type='password']").type("Bad password")
// this should fail
cy.get("form").submit()
cy.route('POST', 'access-tokens', '@loginSuccessResponse').as('loginSuccess')
cy.get("form input[type='password']").type("g00d@password.com")
// this should let me in
cy.get("form").submit()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM