首页 > 其他分享 >WEB自动化-08-Cypress 接口测试

WEB自动化-08-Cypress 接口测试

时间:2022-09-20 23:45:52浏览次数:87  
标签:body WEB url 08 request response cy expect Cypress

8 接口测试

    在服务和服务、系统和系统之间进行通信时,常常会使用到接口。通过接口测试,可以在项目早期更快发现问题。接口有很多类型,而现阶段使用的接口是基于HTTP协议的接口。

8.1 Cypress支持的HTTP请求方式

    在Cypress中发起HTTP请求时,需要使用到的命令为cy.request(),其基本语法格式如下所示:

cy.request(url)
cy.request(url, body)
cy.request(method, url)
cy.request(method, url, body)
cy.request(options)

    主要参数详细信息如下所示:

  • url

    url(String),发起请求的接口地址。需要注意的事项如下所示:

    1、如果cy.request()在cy.visit()后发起请求时,则Cypress将默认使用cy.visit()中的域名做为发起接口请求的域名地址,示例如下所示:

cy.visit('https://www.surpassme.com/app')
cy.request('users/add') //  实际访问的URL: https://www.surpassme.com/users/add

    2、如果事先在cypress.json设置了baseUrl时,则在发送接口请求时,可以不填写域名,Cypress在实际发起请求时,会自动将baseUrl添加到接口地址前面。示例如下所示:

// cypress.json
{
  "baseUrl": "https://www.surpassme.com/
}
cy.request('user/add') // 实际访问的URL: https://www.surpassme.com/users/add

    3、如果Cypress没有检测到域名,则抛错误异常

  • body

    body (String, Object)是发起请求的请求体。根据接口类型,body会有不同的形式。

  • method

    method (String) 是发起请求的方法。默认请求方法为GET,其支持的方法比较多,最常见的有GETPOSTPUTDELETE

  • **options **

    options (Object)是可选项,可以定义一些其他的参数来改变cy.request的一些行为,主要哪下所示:

选项 默认值 功能描述
log true 是否在Command log中显示命令
url null 发起请求的URL地址
method GET 请求方法
auth null 添加鉴权头信息
body null 请求体
failOnStatusCode true 若返回的状态码不是2xx和3xx系列,则认为请求失败
followRedirect true 是否自动重定向
form false 是否以表单形式发送请求体,如果是的话,则设置urlencode为x-www-form-urlencoded
encoding utf8 请求响应的编码方式,支持ascii, base64, binary, hex, latin1, utf8, utf-8, ucs2, ucs-2, utf16le, utf-16le等
gzip true 是否接受gzip编码
headers null 添加额外的请求头
qs null 查询参数,如果填写后,则自动追加到URL地址后面
retryOnStatusCodeFailure false 在通过状态码判定为失败后的重试次数,如果设置为true,则重试4次
retryOnNetworkFailure true 在通过网络问题判定后为失败后的重试次数,如果设置true,则重试4次
timeout responseTimeout 解析域名地址的超时时间
  • 输出内容

    在通过cy.request()发送请求后,输出的响应内容主要有statusbodyheadersduration

8.2 示例

8.2.1 发起GET请求

    GET是平常使用最多的请求,我们来看看示例,如下所示:

/// <reference types="cypress" />

describe('发送GET请求示例', () => {
    let url="http://httpbin.org/get"

    it('发送请求的GET示例用例-1', () => {
        cy.request(url).as("response");
        cy.get("@response").should((response)=>{
            expect(response.body).to.have.property("headers")
            expect(response.body.url).to.eq(url)
            expect(response.body.headers.Host).to.eq("httpbin.org")
        });
    });

    it('发送请求的GET示例用例-2', () => {
        cy.request("GET",url).as("response");
        cy.get("@response").should((response)=>{
            expect(response.body).to.have.property("headers")
            expect(response.body.url).to.eq(url)
            expect(response.body.headers.Host).to.eq("httpbin.org")
        });
    });

    it('发送请求的GET示例用例-3', () => {
        cy.request("GET",url,{"name":"Surpass","age":28}).as("response");
        cy.get("@response").should((response)=>{
            expect(response.body).to.have.property("headers")
            expect(response.body.url).to.contain(url)
            expect(response.body.headers.Host).to.eq("httpbin.org")
        });
    });


    it('发送请求的GET示例用例-4', () => {
        cy.request({
            method:"GET",
            url:url,
            qs:{"name":"Surpass","age":28}
        }).then((response)=>{
           expect(response.body.args.name).to.eq("Surpass")
           expect(response.body.args.age).to.eq("28")
           expect(response.status).to.eq(200)
           expect(response.body.headers.Host).to.eq("httpbin.org")
           expect(response.body).to.have.property("headers")
        });
    });

    it('获取图片示例', () => {
        cy.request({
            method:"GET",
            url:"https://www.cnblogs.com/images/logo.svg",
            encoding:"base64"
        }).then((response) => {
            let base64Content=response.body;
            let mime=response.headers["content-type"];
            let imageDataUrl=`data:${mime};base64,${base64Content}`
        })
    });

    it('下载文件', () => {
      cy.request({
          method:"GET",
          url:"https://www.cnblogs.com/images/logo.svg",
          encoding:"binary"
      }).then((response)=>{
          cy.writeFile("./cnblog.logo.svg",response.body,"binary");
      })
    });
});

    运行结果如下所示:

8.2.1 发起POST请求

    示例如下所示:

/// <reference types="cypress" />

describe('发送POST请求示例', () => {
    let url="http://httpbin.org/post";
    let body={"name":"Surpass","age":28};

    it('发送请求的POST示例用例-1', () => {
        cy.request("POST",url,body).as("response");
        cy.get("@response").should((response)=>{
             expect(response.body.json.name).to.eq("Surpass")
             expect(response.body.headers.Host).to.eq("httpbin.org")
        })
    });

    it('发送请求的POST示例用例-2', () => {
        cy.request({
           method:"POST",
           url:url,
           body:body,
           form:true
        }).then((response)=>{
            expect(response.body.form.name).to.eq("Surpass")
            expect(response.body.headers.Host).to.eq("httpbin.org")
        });
    });

    it('发送请求的POST示例用例-3', () => {
        cy.request({
           method:"POST",
           url:url,
           body:body,
           form:false,
           headers:{"Content-Type":"application/json","Customer-Header":"Surpass"}
        }).then((response)=>{
            expect(response.body.json.name).to.contain("Surpass")
            expect(response.body.headers.Host).to.eq("httpbin.org")
            expect(response.headers["content-type"]).to.eq("application/json")
            expect(response.body.headers["Customer-Header"]).to.eq("Surpass")
        });
    });
});

    运行结果如下所示:

原文地址:https://www.jianshu.com/p/007976277dc8

本文同步在微信订阅号上发布,如各位小伙伴们喜欢我的文章,也可以关注我的微信订阅号:woaitest,或扫描下面的二维码添加关注:

标签:body,WEB,url,08,request,response,cy,expect,Cypress
From: https://www.cnblogs.com/surpassme/p/16714101.html

相关文章

  • Java基础08 自增自减运算符、初识Math类
    publicstaticvoidmain(String[]args){//++--自增自减一元运算符inta=3;intb=a++;//执行完这行代码后,先给b赋值,再自......
  • web项目心得
    1、浏览器检查查看接口信息,发现看不到状态码等信息,则跨域失败了......
  • P8283 「MCOI-08」Dantalion 解题报告
    P8283「MCOI-08」Dantalion解题报告:最近好像有很多人做这道题,把这题题解发一下吧。可能说的比较啰嗦,见谅。题意给定序列\(a\),\(q\)次询问一个区间有多少个子区间在......
  • 2022-08-30 第二小组 张鑫 学习笔记
    实训五十二天Servlet学习内容HttpServletRequest//请求  所有和请求相关的操作  当请求来的时候,request就被实例化HttpServletResponse//响应  所有和......
  • Luogu T273083 新的题目 题解
    怕放洛谷有人看,就搬过来了。本题解提供一个\(O(qn)\)的做法(实际上是暴力的优化)。先考虑暴力求解。对于每个操作,要求代价\(W\times(\sum_{i\inX}^{i}w[i]\times......
  • Centos 7 web 环境搭建
    1、Xshell5为了方便管理操作服务器,这里采用xshell5来连接服务器,使用ssh证书,端口号22,对于购买的与主机需要开放相应的端口。如下是连接成功的提示:[c:\~]$openCon......
  • webstrom ——activation code (最新2022.9.20)
    右键-->全选-->复制,粘贴到Activationcode中4U1192YQAG-eyJsaWNlbnNlSWQiOiI0VTExOTJZUUFHIiwibGljZW5zZWVOYW1lIjoi5rC45LmF5r+A5rS7IHd3d8K3YWppaHVvwrdjb20iLCJhc3NpZ2......
  • .net通过数据流的方式,HttpWebRequest请求小程序二维码
    #region///<summary>///获取小程序页面的小程序码不限制///</summary>///<paramname="accessTokenOrAppId">AccessToken或App......
  • .NET 6 EFCore WebApi 使用 JMeter 进行吞吐量测试
    .NET6EFCoreWebApi使用JMeter进行吞吐量测试开发环境VS2022.NET6测试环境测试工具接口压力测试工具:JMeter数据库MySQL5.7数据库和WebApi服务在同一台服务......
  • 做题记录整理dp3 P1108. 低价购买(2022/9/20)
    P1108.低价购买第一问很明显是一个最长下降子序列第二问就是一个求方案数,有点难想的就是去重感觉这题难度标的有点偏高#include<bits/stdc++.h>#definefor1(i,a,b)......