官方:https://example.cypress.io/commands/assertions
expect
作用
To make a BDD assertion about a specified subject, use expect.
匹配具体的对象
示例代码
// https://on.cypress.io/assertions
it('expect - make an assertion about a specified subject', () => {
// 可以使用chai的BDD断言风格
expect(true).to.be.true
const o = { foo: 'bar' }
expect(o).to.equal(o)
expect(o).to.deep.equal({ foo: 'bar' })
// 使用正则表达式匹配文本
expect('FooBar').to.match(/bar$/i)
})
assert
作用
To make a TDD assertion about a specified subject, use assert.
示例代码
断言一个对象的形状
const person = {
name: 'Joe',
age: 20,
}
assert.isObject(person, 'value is object')
.should(cb)
作用
将复杂的断言写成一个函数,然后传给should,回调函数会一直执行直到所有显式断言通过或超时。
示例代码1-给should传回调函数
cy.get('.assertions-p').find('p')//找到p标签 一共有3个
.should(($p) => {
// 从p标签中返回text数组
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()
// 数组的长度为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',
])
})
示例代码2 --通过className找元素
断言元素的class属性包含heading-.
cy.get('.docs-header').find('div') //找到class为docs-header下的div标签
// .should(cb) 下的回调函数失败后会重试
.should(($div) => { //$div 表示div标签
expect($div).to.have.length(1) //断言只有1个div标签
const className = $div[0].className //获取div标签的className
expect(className).to.match(/heading-/) //断言className包含字符串heading- 前后/表示正则
})
// .then(cb) 的回调函数不会重试 要么失败要么成功
// it either passes or fails
.then(($div) => {
expect($div).to.have.text('Introduction') //断言标签的text
})
示例代码3-抛出错误
cy.get('.docs-header').find('div')
.should(($div) => {
if ($div.length !== 1) { //如果div标签长度不为1 即div标签为0个
// 抛出错误
throw new Error('Did not find 1 element')
}
const className = $div[0].className //定义变量
if (!className.match(/heading-/)) { //如果标签的className不匹配
throw new Error(`Could not find class "heading-" in ${className}`)
}
})
示例代码4-对比两个元素的text
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)
})
示例5
cypress只会重试最后的命令,如果你想在执行断言前执行另外的步骤,你可以用回调函数让多个操作重试。
cy.get('#random-number')
.should(($div) => {
// retries getting the element
// while the "🎁" is converted into NaN
// and only passes when a number is set
const n = parseFloat($div.text())
expect(n).to.be.gte(1).and.be.lte(10)
})