如果想从头学起Cypress,可以看下面的系列文章哦
https://www.cnblogs.com/poloyy/category/1768839.html
发起一个 HTTP 请求
cy.request(url)
cy.request(url, body)
cy.request(method, url)
cy.request(method, url, body)
cy.request(options)
请求 URL
// 先访问某个 url
cy.visit('http://localhost:8080/app')
// 请求 url 是 http://localhost:8080/users/1.json
cy.request('users/1.json')
cypress.json
// cypress.json
{
"baseUrl": "http://localhost:1234"
}
测试代码
// url 是 http://localhost:1234/seed/admin
cy.request('seed/admin')
如果 cypress 无法确定 host,它将抛出错误
请求方法,没啥好说的,默认是 GET
context('get请求', function () {
it('默认访问方式', function () {
cy.request('http://www.helloqa.com')
});
it('使用 options', function () {
cy.request({
method: 'get',
url: 'http://www.helloqa.com'
})
});
// .request() 常常和别名 .as() 一起使用,用来进行接口返回值的断言
it('真实测试', function () {
cy.request({
method: 'get',
url: 'https://www.helloqa.com'
}).as('comments')
cy.get('@comments')
.then((response) => {
expect(response.status).to.be.eq(200)
})
});
})
包含以下属性
包含以下属性
有时候,cy.request() 测试页面的内容要比 cy.visit() 更快,然后等待整个页面加载所有资源
const username = 'jane.lane'
const password = 'password123'
it('使用 visit', function () {
// 相当于 UI 界面操作
cy.visit('')
// 登录操作
cy.get("input[name=username]").type(username)
cy.get("input[name=password]").type(password)
cy.get("form").submit()
// 会跳转至需要登录才能访问的页面
cy.get("h1").should("contain", "jane.lane") });
it('request代替visit', function () {
// 通过接口层面去访问页面
// 请求页面
cy.request('/login')
.its('body')
.should('include', '<p>In this recipe we:</p>')
// 登录请求
cy.request({
method: 'post',
url: '/login',
// 表单格式的请求
form: true,
body: {
username: 'jane.lane',
password: 'password123'
}
})
// 访问需要登录之后才能访问的页面
cy.request('/dashboard')
.its('body')
.should('include', 'jane.lane')
});
通常,一旦对登录进行了适当的e2e测试,就没有理由继续使用 cy.visit() 登录并等待整个页面加载所有关联的资源,然后再运行其他命令,这样做可能会减慢我们整个测试套件的速度
function req() {
cy
.request('/')
.then((resp) => {
if (resp.status === 200)
// 请求成功则退出轮询
return
// 递归
req()
})
}
context('轮询request', function () {
it('默认访问方式', function () {
cy.visit('http://localhost:7077/')
// 轮询前的操作
cy.get("form").click()
// 轮询请求
.then(() => {
req()
})
});
})
.request()
.request()