Cypress接口自动化4-定义数组接口驱动化
- 2021-09-22 17:00:00
- wencheng
- 转贴:
- 微信公众号
- 4212
前言
自动化测试里面参数化思想是非常重要的,同一类型的测试,只需维护不同的数据就可以了。策略一:数据通过数组的方式创建
/** * Create by dell on 2021/ 4/8 * Author :wencheng * describe : * */ describe("定义数组接口驱动化", function () { beforeEach("获取token", function () { cy.token() }) let testDatas = testDatas = [ { 'casename': '获取配置列表信息', 'url': '/configures/', 'method': 'GET', 'headers': '{"Content-Type": "application/json", "authorization": "JWT token"}', 'body': '', 'status_code': 200 }, { 'casename': '获取项目(多个)列表数据', 'url': '/projects/', 'method': 'GET', 'headers': '{"Content-Type": "application/json", "authorization": "JWT token"}', 'body': '', 'status_code': 200 }, { 'casename': '返回所有项目ID和名称', 'url': '/projects/names/', 'method': 'GET', 'headers': '{"Content-Type": "application/json", "authorization": "JWT token"}', 'body': '', 'status_code': 200 } , { 'casename': '创建项目', 'url': '/projects/', 'method': 'POST', 'headers': '{"Content-Type": "application/json", "authorization": "JWT token"}', 'body': '{"name": "randomname", "leader": "张三", "tester": "李四","programmer": "王五", "publish_app": "测测测", "desc": "randomdesc"}', 'status_code': 201 } ] for (const data in testDatas) { it(`${testDatas[data].casename}`, function () { var token = sessionStorage.getItem("Token") var url = testDatas[data].url var method = testDatas[data].method var headers = testDatas[data].headers var body = testDatas[data].body var status_code = testDatas[data].status_code //封装http请求 cy.requests(url, method, headers, body, token, status_code) }); } })
二次封装http请求
Cypress.Commands.add("requests", function (url, method, header, body, token, status_code) { cy.log('测试地址: ' + url) cy.log('请求参数: ' + body) cy.log('请求方法: ' + method) cy.log('请求头部: ' + header) var headers = JSON.parse(header.replace('token', token)) if (method.toUpperCase() == "GET") { cy.request({ url: url, method: method, headers: headers, body: body }).then(function (resp) { cy.log("返回结果:" + JSON.stringify(resp.body)) expect(resp.status).to.eq(status_code) }) } else if (method.toUpperCase() == "POST") { //随机名称 var randomName = require("chinese-random-name"); var randomname = randomName.names.get3() var bodys = body.replace('randomname', randomname) var body = JSON.parse(bodys) cy.request({ url: url, method: method, headers: headers, body: body }).then(function (resp) { cy.log("返回结果:" + JSON.stringify(resp.body)) expect(resp.status).to.eq(status_code) }) } })
token
//全局定义获取token Cypress.Commands.add('token', function () { cy.request({ url: "http://api.keyou.site:8000/user/login/", method: 'POST', headers: {"Content-Type": "application/json"}, body: {"username": 'keyou1', "password": '123456'} }) .its('body.token').as('token') .then(function () { cy.wrap(sessionStorage.setItem("Token", this.token)); }) cy.log("返回的token:" + sessionStorage.getItem("Token")) })
运行结果
发表评论
联系我们
- 联系人:阿道
- 联系方式: 17762006160
- 地址:青岛市黄岛区长江西路118号青铁广场18楼