Home > Software design >  same api, but different response in cypress
same api, but different response in cypress

Time:01-10

Can cypress version 6 handle same api, but diff responses? If yes, is the following correct? If we cannot, will cypress version 9 support this?

// * same api for each test, but diff response
const api = '/v1/test';

it('test 1', () => {
    cy.intercept(api, {res: '1'});
    // do stuff
});

it('test 2', () => {
    cy.intercept(api, {res: '2'});
    // do stuff
});

it('test 3', () => {
    cy.intercept(api, {res: '2'});
    // do stuff
});

There are some hacking, but looking for a proper way.

CodePudding user response:

You can examine the "routes" by adding this code

afterEach(() => {
  const routes = cy.state('routes')
  const keys = Object.keys(routes)
  console.log('Number of routes', keys.length)  // 1, 1, 1 - only one route exists per test
  const route = routes[keys[0]]
  console.log(route.handler.body)             // {res: '1'}, {res: '2'}, {res: '2'}
})

Note, the referenced question is about cy.route() which has less capability than cy.intercept()

CodePudding user response:

From the cy.intercept() page,

All intercepts are automatically cleared before every test.

So, if you are setting your intercepts on a per-test basis (in the it() blocks), then this should work as you'd expect, with each test having a different response for the same endpoint. As far as I know, this been the behavior of cy.intercept() since it was introduced, and should work with Cypress 6.

  • Related