Cypress 系列之----03 常用API


Cypress 的所有command都是異步的

元素選擇和操作

方法 功能 范例 參考
contains(content) 獲取單元素 - 通過文本 cy.get('.nav').contains('About')
cy.contains('Hello')
cy.contains(/^b\w+/)
get(selector|alias) 獲取多元素
通過CSS選擇器 | 別名
CSS選擇器支持jquery語法
cy.get('.list > li’)
cy.get('ul li:first')
cy.get('[data-test-id="test-example"]')
within(fn) 連綴處理元素 - 函數 cy.get('.list').within(() =>{...})
find(selector) 連綴處理元素 - 選擇器 cy.get('.list').find('>li')
children 獲取子元素 cy.get('nav').children()
parent() 獲取父元素 cy.get('header').parent()
parents() 獲取所有的父節點 cy.get('aside').parents()
closest 獲取第一個匹配的元素 cy.get('td').closest('.filled')
eq(index) 序號 | 序列中的元素
filter(selector) 過濾元素 cy.get('td').filter('.users')
not() 過濾元素 和filter相反
first() 返回第一個元素 cy.get('nav a').first()
last() 返回最后一個元素 cy.get('nav a').last()
next() 下一個元素 cy.get('nav a:first').next()
nextAll() 接下來所有
nextUntil() 接下來直到
prev() 前一個元素 cy.get('li').prev('.active')
prevAll()
prevUntil()
url 獲取當前頁面 url
title 獲取當前頁面標題
window元素
document 獲取window.document
location 獲取window.location查詢 cy.location('host')
params&query cy.location('port')
可用參數:
hash | host | hostname
| href | origin | pathname
| port | protocol | search
| toString
Cypress.browser window.browser

元素內容處理

方法 功能 范例 參考
each(callbackFn) 遍歷 cy.get('ul>li').each(function () {...})
clear 清除元素內容 cy.get('[type="text"]').clear()
//清除內容 賦予新值
cy.get('input[name="name"]').clear().type('Jane Lane')
type( txt[,options]) } 模擬輸入內容 cy.get('input').type(' 233 ')
cy.get('input').type('{shift}{alt}Q')---組合鍵盤操作
cy.get('input').type('{alt}這里是按了一下alt后輸入的內容')
fixture(filePath, encoding, options) 讀取文件 cy.fixture('users.json').as('usersData')
cy.fixture('users')
.then((json) => {
cy.route('GET', '/users/**', json)
})

元素操作事件

方法 功能 范例 參考
trigger 觸發DOM元素 cy.get('a').trigger('mousedown')
visit 訪問鏈接 cy.visit('landing')
根據情況拼接
設置過baseUrl就是baseUrl+landing
沒設置過就是直接訪問
cy.visit('lesson_report/807212') 活動路由
click 單擊
dblclick 雙擊 cy.focused().dblclick()
focus 聚焦 cy.get('input').first().focus()
blur 失焦
check 選中選項 限定: checkbox/radio
uncheck 取消選中 cy.uncheck()
select 選擇選項
限定option
cy.get('select').select('user-1')
end 清空返回值 用於繼續連綴 cy .get('#a').click().end() .get('#b').click()
等價於
cy.get('#a').click() cy.get('#b').click()
exec 執行原生事件 cy.exec('npm run build').then((result) => { ... }
focused
reload 刷新 cy.reload() // 普通刷新
cy.reload(forceReload) //強刷

數據請求 | 數據處理

方法 功能 范例 參考
server()
route(options) 參數 cy.route(url)
cy.route(url, response)
cy.route(method, url)
cy.route(method, url, response)
cy.route(callbackFn)
cy.route(options)
clearCookie(name[,options]) 清除選定cookie
默認會清除
一般用不到
cy.clearCookie('authId')
clearCookies 清除所有cookie
clearLocalStorage 清除localstorage
request(method, url, body) 數據請求 參考
存在cypress.json的baseUrl
baseUrl作為主機
// cypress.json {"baseUrl": "http://localhost:1234"} // spec.js cy.request('seed/admin')http://localhost:1234/seed/ad
沒有cypress.json的baseUrl
上一個visit的網址作為主機
cy.visit('http://localhost:8080/app')
cy.request('users/1.json') http://localhost:8080/users/1.json
wrap 傳值測試 const getName = () => { return 'Jane Lane'}
cy.wrap({ name: getName }).invoke('name').should('eq', 'Jane Lane') // true

其他

方法 功能 范例 參考
debugger 要在 then() 里調用
task() 通過插件事件在Node.js中執行代碼task。
exec() 執行Shell
config() 在測試中獲取和設置配置選項 Cypress.config()
Cypress.config(name)
Cypress.config(name, value)
Cypress.config(object)
as( str ) 設置別名 不能單獨使用 cy.route('PUT', 'users', 'fx:user').as('putUser')
cy.get('.main-nav').find('li').first().as('firstNav')
this.alias @alias 使用別名 簡寫符號@ cy.get('.contain').as('c') cy.get('this.c').find('input')
等價於
cy.get('@c').find('input')
clock( ) 時間有關的各種 * setTimeout * clearTimeout * setInterval * clearInterval * Date 對象 cy.clock()
cy.clock(now)
cy.clock(now, functionNames)
cy.clock(options)
cy.clock(now, options)
cy.clock(now, functionNames, options)
clock.tick( time ) 時間偏移量 cy.clock()
cy.visit('/index.html')
cy.tick(1000)
cy.get('#seconds-elapsed')
.should('have.text', '1 seconds') cy.tick(1000) cy.get('#seconds-elapsed')
.should('have.text', '2 seconds')
clock.restore()
go 前進后退 cy.go('back') cy.go(1)
hover 禁止使用(有BUG) cy.get('.menu-item').trigger('mouseover') cy.get('.popover').should('be.visible')
可以使用trigger模擬
invoke 調用函數的別名 cy .wrap({ animate: fn }) .invoke('animate')
注意 別名必須先出現
its 調用元素別名 cy .wrap({ width: '50' }).its('width')
獲取元素數量,元素屬性,sessionStorage等 https://docs.cypress.io/api/commands/its.html#Command-Log // Get the 'width' property cy .window().its('sessionStorage')
// Get the 'sessionStorage' property cy .wrap({ age: 52 })
.its('age').should('eq', 52)
// true
cy .get('ul li').its('length') .should('be.gt', 2)}) cy.request(...) .its('body.user') .then(user => ...)
cy .title().its('length').should('eq', 24)
log 打印log cy.log('created new user’)
cy.log( str, args )
cy.log('events triggered', events)
pause 暫停 - 暫停運行 可以手動操作
resume 恢復 - 繼續運行
then 處理前綴yield的內容 cy.get('button')
.then(($btn) => { const cls = $btn.class() cy.wrap($btn).click()
.should('not.have.class', cls) })

補充 - 斷言相關的語法

方法 功能 范例 參考
should 斷言 cy.get('.btn').should('be.empty') cy.get('.greeting').should('not.be.visible')
cy.get('.btn') .should((text2) => { expect(text1).not.to.eq(text2) })
cy.get('option:first') .should('be.selected') .then(($option) => { ... })
cy.request('/users/1').its('body').should('deep.eq', { name: 'Jane' })
value id | class | value cy.get('input') .should('have.class', 'btn')
cy.get('input') .should('not.have.value', 'Jane')
cy.get('button') .should('have.id', 'a') .then(($button) => { // $button is yielded })
Method and Value cy.get('#header a') .should('have.attr', 'href', '/users')
Focus cy.get('#ipt') .should('have.focus')
Function 看官網
斷言樣式 cy.get('div').should('have.css','color','blue')
斷言文本 完全匹配 cy.get('div').should('have.text', 'foobarbaz')
斷言文本 部分匹配|包含 cy.get('div').should('contain', 'foobarbaz')
斷言之前使用文本 cy.get('div').should(($div) => {
const text = $div.text()
expect(text).to.match(/foo/)
expect(text).to.include('foo')
expect(text).not.to.include('bar') })
保留引用 or 比較文本值 cy.get('div').invoke('text') .then((text1) => { cy.get('button').click() //text change cy.get('div').invoke('text') .should((text2) => { expect(text1).not.to.eq(text2) }) })
cy.get('#header a') .should('have.class', 'active') .and('have.attr', 'href', '/users')
獲取innerText cy.get('div').should(($div) => { // access the native DOM element expect($div.get(0).innerText).to.eq('foobarbaz') })


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM