zoukankan      html  css  js  c++  java
  • [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('/');
    });
  • 相关阅读:
    基于layui的简易后台管理系统,后期会更新
    java基础语法知识(笔记)——(一)基本变量类型,循环,日期类
    JavaWeb学习总结(笔记)——SSM spring.xml的基本配置
    JavaWeb学习总结(笔记)——SSM中Web.xml文件
    JavaWeb学习总结(笔记)——SSM关键类及其作用
    JavaWeb学习总结(笔记)——关于SSM CRUD上传功能的总结
    JavaWeb——MVC与三层结构
    jquery结合highcharts插件显示实时数据动态曲线图
    jquery结合Highcharts插件实现动态数据仪表盘图形化显示效果
    在IE6/7下表格td标签没有内容时不显示边框?
  • 原文地址:https://www.cnblogs.com/Answer1215/p/15759648.html
Copyright © 2011-2022 走看看