Cypress web自动化6- Assertions断言使用(should, expect)
前言
每个测试用例需要加断言,Cypress里面断言常用的有should, expect
隐式断言
.should()
可以使用.should()给当前用例加断言
- should('have.class', 'success') 断言元素的class属性值是 'success'
- should('have.text', 'Column content') 断言元素文本值 'Column content'
- should('contain', 'Column content') 断言元素文本包含 'Column content'
- should('have.html', 'Column content') 断言元素html文本'Column content'
- should('match', 'td') chai-jquery 使用 "is()"检查元素是否与选择器匹配
- .invoke('text')
.should('match', /column content/i) 文本与正则表达式匹配先使用invoke结合should - .contains('text') 文本与正则表达式匹配元素文本包含,这种比上面更好
<table class="table table-bordered assertion-table">
<thead>
<tr>
<th>#</th>
<th>Column heading</th>
<th>Column heading</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td>Column content</td>
<td>Column content</td>
</tr>
<tr>
<th scope="row">2</th>
<td>Column content</td>
<td>Column content</td>
</tr>
<tr class="success">
<th scope="row">3</th>
<td>Column content</td>
<td>Column content</td>
</tr>
</tbody>
</table>
cy.get('.assertion-table')
.find('tbody tr:last').should('have.class', 'success')
.find('td')
.first()
// checking the text of the element in various ways
.should('have.text', 'Column content')
.should('contain', 'Column content')
.should('have.html', 'Column content')
// chai-jquery uses "is()" to check if element matches selector
.should('match', 'td')
// to match text content against a regular expression
// first need to invoke jQuery method text()
// and then match using regular expression
.invoke('text')
.should('match', /column content/i)
// a better way to check element's text content against a regular expression
// is to use "cy.contains"
// https://on.cypress.io/contains
cy.get('.assertion-table')
.find('tbody tr:last')
// finds first element with text content matching regular expression
.contains('td', /column content/i)
.should('be.visible')
.and()
针对同一元素多个断言,可以使用 and 语法
cy.get('.assertions-link')
.should('have.class', 'active')
.and('have.attr', 'href')
.and('include', 'cypress.io')
显示断言
expect()
针对项目 BDD 断言方式
expect(true).to.be.true
const o = { foo: 'bar' }
expect(o).to.equal(o)
expect(o).to.deep.equal({ foo: 'bar' })
// matching text using regular expression
expect('FooBar').to.match(/bar$/i)
assert()
针对项目 BDD 断言方式
const person = {
name: 'Joe',
age: 20,
}
assert.isObject(person, 'value is object')
Should with callback function
下面这段我也看不懂了,不翻译了
You can write your own complicated checks using .should(cb) function if included assertions are not enough. Pass a function to should() with any number of explicit assertions within it. The callback function will be retried until it passes all your explicit assertions or times out.
cy.get('.assertions-p').find('p')
.should(($p) => {
// return an array of texts from all of the p's
let texts = $p.map((i, el) => // https://on.cypress.io/$
Cypress.$(el).text())
// jquery map returns jquery object
// and .get() convert this to simple array
texts = texts.get()
// array should have length of 3
expect(texts).to.have.length(3)
// use second argument to expect(...) to provide clear
// message with each assertion
expect(texts, 'has expected text in each paragraph').to.deep.eq([
'Some text from first p',
'More text from second p',
'And even more text from third p',
])
})
Assert that element's class includes heading-.
cy.get('.docs-header').find('div')
// .should(cb) callback function will be retried
.should(($div) => {
expect($div).to.have.length(1)
const className = $div[0].className
expect(className).to.match(/heading-/)
})
// .then(cb) callback is not retried,
// it either passes or fails
.then(($div) => {
expect($div).to.have.text('Introduction')
})
You can throw any error from the callback function. The callback will be retried, but the assertions will not be shown as nicely in the Command Log UI as Chai assertions.
cy.get('.docs-header').find('div')
.should(($div) => {
if ($div.length !== 1) {
// you can throw your own errors
throw new Error('Did not find 1 element')
}
const className = $div[0].className
if (!className.match(/heading-/)) {
throw new Error(`Could not find class "heading-" in ${className}`)
}
})
We strongly recommend that your tests are deterministic. But sometimes you might need to match text between two elements, and you do not know what that text should be. Save the value from the first element, then compare it from a should(cb) callback.
let text
/**
* Normalizes passed text,
* useful before comparing text with spaces and different capitalization.
* @param {string} s Text to normalize
*/
const normalizeText = (s) => s.replace(/\s/g, '').toLowerCase()
cy.get('.two-elements')
.find('.first')
.then(($first) => {
// save text from the first element
text = normalizeText($first.text())
})
cy.get('.two-elements')
.find('.second')
.should(($div) => {
// we can massage text before comparing
const secondText = normalizeText($div.text())
expect(secondText, 'second text').to.equal(text)
})
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
2019-05-11 appium+python自动化64-使用Uiautomator2执行driver.keyevent()方法报错解决
2018-05-11 appium+python自动化45-夜神模拟器连不上(adb server version (36) doesn't match this client (39); killing...)