[Cypress] intercept()

Simulate a network error using .intercept() command

You can simulate a network condition, where an http request does not make it to server. When that happens, you want to make sure the app is showing the user a correct message. By passing forceNetworkError attribute, you’ll be able to simulate such network conditions and see how application behaves under given circumstances.

it('shows error when board cannot be displayed', () => {
  cy.intercept({
      method: 'GET',
      url: '/api/boards'
    }, {
      forceNetworkError: true
    }
  ).as('boards');

  cy.visit('/');

  cy.get('[data-cy=board-list-error-message]').should('be.visible');
});

 

Stub an API Request Status Code and Error Message with cy.intercept

Frontend application can react differently to various server responses. One way to test the application behavior is to change response status code. .intercept() command in Cypress has the ability to stub the status code and error message that the server would provide on error.

it('intercept status code', () => {
  cy.intercept('/api/boards', {
    statusCode: 500,
    body: {
      message: 'Oops something went wrong!'
    }
  }).as('boards');
  cy.visit('/');
});

 

Use a Fixture in Cypress to Provide Response Data to Network Requests

Instead of explicitly providing the exact body, you can choose to save the data you want to use in a separate file. When you create a file in the fixtures folder, you can reference it using fixture option in the .intercept() command. This will automatically look into the fixtures folder and load the data from the file.

it('intercept body with fixture', () => {
  cy.intercept('GET', '/api/boards', {
    fixture: 'customList'
  }).as('boards');
  cy.visit('/');
});

You need to create a customList.json file in fixtures folder.

 

Configure cy.intercept to Only Intercept a Network Request Once

When testing certain user stories, you may want to start with a clean state, but then return to the initial page and see the data you have created. This can be problematic if you are stubbing your requests. Luckily, you can limit how many times you a request should be intercepted.

it('intercept once', () => {
  cy.intercept({
    method: 'GET', 
    url: '/api/boards',
    times: 1
  }, {
    body: []
  }).as('boards');
  cy.visit('/');

  cy.get('[data-cy=first-board]')
    .type('rocket launch{enter}')

  cy.get('[data-cy=home]')
    .click()
});

 

Dynamically Combine Real and Mocked Response Body Data in Cypress

When a static response is not enough, we can take the real data from server and modify it to our liking. This saves a ton of time, because we don’t need to create the data ourselves. Instead, we can take e.g. response body and change only a desired attribute. This gives us one more advantage, because we can first make assertions on real data, and only then make changes. This is a great advantage compared to providing a static response, that essentially creates a blind spot for any API changes.

it('intercept query', () => {
  cy.intercept('/api/boards', (req) => {
    req.query = {
      starred: 'false'
    }
  }).as('boards');
  cy.visit('/');
});

 

Dynamically Combine Real and Mocked Response Body Data in Cypress

When a static response is not enough, we can take the real data from server and modify it to our liking. This saves a ton of time, because we don’t need to create the data ourselves. Instead, we can take e.g. response body and change only a desired attribute. This gives us one more advantage, because we can first make assertions on real data, and only then make changes. This is a great advantage compared to providing a static response, that essentially creates a blind spot for any API changes.

it('intercept body dynamically', () => {
  cy.intercept('/api/boards', (req) => {
    req.reply( res => {
      expect(res.body[0].name).to.exist
      res.body[0].name = 'Filip’s birthday party'
    })
  }).as('boards');
  cy.visit('/');
});

 

Prevent Response Caching in Cypress by Deleting 'if-none-match' Request Header

Servers sometimes use entity tags that identify a user and provide them with a cached response if needed. This can create ambiguity in your tests. To make your tests more stable, you can modify the request headers that take care of this caching. By deleting if-none-match header with .intercept() command, you will get a fresh response from server every time.

it('handling a cached response', () => {
  cy.intercept('/api/boards', (req) => {
    delete req.headers['if-none-match']
  }).as('boards')
  cy.visit('/');
  cy.wait('@boards')
    .its('response.statusCode')
    .should('eq', 200)
});

 

Test Slow Network Conditions in Cypress by Throttling and Delaying Intercepted Requests

When user waits too long, we might want to give them an option to reload page and try again. This is usually a hard case to reach and test effectively. But the .intercept() command provides us with a throttleKbps option that can limit the bandwidth, or we can use delay option that will delay our response for a given time.

it('delays a request', () => {
  cy.intercept({
    url: '/api/boards',
    times: 1
  }, (req) => {
    req.reply( (res) => {
      res.delay = 5000
    })
  }).as('boards');
  cy.visit('/');
  cy.contains('This is taking too long.')
    .should('be.visible')
  cy.contains('Reload')
    .click()
});

 

Send Network Requests with Authorization Headers in an Intercepted Request with Cypress

Server may respond differently when providing a response to a logged in user. Usually, a user is identified when an authorization header is sent with the request. With .intercept(), we can dynamically add a header to a request and skip the login process. Server will provide the same response as it would when a user would go through login process.

 
it('loads all data', () => {
  cy.intercept('/api/boards', (req) => {
    req.headers['Authorization'] = 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImZpbGlwQGV4YW1wbGUuY29tIiwiaWF0IjoxNjM2NTc3NjQzLCJleHAiOjE2MzY1ODEyNDMsInN1YiI6IjEifQ.CF3roP17bJcc0aiJPWsFLOo211iWXTBcSRNw1xwbBek'
  }).as('boards');
  cy.visit('/');
});

 

上一篇:C#实现文本文件读写及程序发布


下一篇:Filter过滤器及其作用