[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('/');
});

 

posted @   Zhentiw  阅读(423)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2019-01-03 [Unit Testing] Mock a Node module's dependencies using Proxyquire
2019-01-03 [SCSS] Create a gradient with a Sass loop
2018-01-03 [Poi] Build and Analyze Your JavaScript Bundles with Poi
2018-01-03 [Poi] Use Markdown as React Components by Adding a Webpack Loader to Poi
2018-01-03 [Poi] Build a Vue App with Poi
2018-01-03 [Poi] Customize Babel to Build a React App with Poi
2016-01-03 [ES6] Object.assign (with defaults value object)
点击右上角即可分享
微信分享提示