安装插件cypress-commands
npm install cypress-commands
将cypress-commands导入项目中 cypress/support/index.js
import 'cypress-commands'
***.to() 字符类型转换***
*语法:*
```javascript
.to(type)
.to(type, options)
正确用法
cy.wrap('00123').to('number'); // 结果 123
cy.wrap(42).to('string'); // 结果 '42'
cy.wrap({ passive: 'Parakeet' }).to('string'); // 结果 '{"passive":"Parakeet"}'
cy.wrap('Underwhelming Uakari').to('array'); // 结果 ['Underwhelming Uakari']
将获取的结果转换成数组再遍历数组
cy.get('.maybeOneElement')
.text()
.to('array')
.each((text) => {
// ...
});
.request() 发送request请求
语法:
cy.request(url)
cy.request(url, body)
cy.request(method, url)
cy.request(method, url, body)
cy.request(options)
用法:
cy.request('http://dev.local/seed')
如果你在.visit()后使用可以省去host
cy.visit('http://localhost:8080/app')
cy.request('users/1.json') // url is http://localhost:8080/users/1.json
如果你在Cypress.json中已经设置了baseUrl也可省去host
// cypress.json
{
"requestBaseUrl": "http://localhost:1234"
}
cy.request('seed/admin') // url is http://localhost:1234/seed/admin
支持的请求方式
- GET
- POST
- PUT
- DELETE
- PATCH
- HEAD
- OPTIONS
- TRACE
- COPY
- LOCK
- MKCOL
- MOVE
- PURGE
- PROPFIND
- PROPPATCH
- UNLOCK
- REPORT
- MKACTIVITY
- CHECKOUT
- MERGE
- M-SEARCH
- NOTIFY
- SUBSCRIBE
- UNSUBSCRIBE
- SEARCH
- CONNECT
参数列表
响应属性
- status
- body
- headers
- duration
beforeEach(function () {
cy.request('http://localhost:8080/db/seed')
})
cy.request('/admin').its('body').should('include', '<h1>Admin</h1>')
DELETE 请求
cy.request('DELETE', 'http://localhost:8888/users/827')
发送POST带有json正文的请求
cy
.request('POST', 'http://localhost:8888/users/admin', { name: 'Jane' })
.then((response) => {
// response.body is automatically serialized into JSON
expect(response.body).to.have.property('name', 'Jane') // true
})
禁用自动重定向时请求页面
cy.request({
url: '/dashboard',
followRedirect: false // turn off following redirects
})
.then((resp) => {
// redirect status code is 302
expect(resp.status).to.eq(302)
expect(resp.redirectedToUrl).to.eq('http://localhost:8082/unauthorized')
})
使用表单选项提交HTML表单
通常,一旦您对登录进行了适当的e2e测试,就没有理由继续cy.visit()登录并等待整个页面加载所有关联的资源,然后再运行其他命令。这样做会减慢我们整个测试套件的速度。
使用cy.request(),我们可以绕开所有这些,因为它会自动获取并设置cookie,就像请求来自浏览器一样。
cy.request({
method: 'POST',
url: '/login_with_form', // baseUrl is prepended to url
form: true, // indicates the body should be form urlencoded and sets Content-Type: application/x-www-form-urlencoded headers
body: {
username: 'jane.lane',
password: 'password123'
}
})
// just to prove we have a session
cy.getCookie('cypress-session-cookie').should('exist')
请求轮询
当您轮询服务器以获取可能需要一段时间才能完成的响应时,此功能很有用。
我们在这里真正要做的就是创建一个递归函数。没有比这更复杂的了。
// just a regular ol' function folks
function req () {
cy
.request(...)
.then((resp) => {
// if we got what we wanted
if (resp.status === 200 && resp.body.ok === true)
// break out of the recursive loop
return
// else recurse
req()
})
}
cy
// do the thing causing the side effect
.get('button').click()
// now start the requests
.then(req)