Skip to main content
Cypress应用

Cypress.sinon

Cypress 自动包含 Sinon.JS 并将其暴露为 Cypress.sinon。由于命令 cy.spycy.stub 已经封装了 Sinon 的方法,Cypress.sinon 最常见的用途是在进行断言时提供灵活的 匹配器

语法

Cypress.sinon.match(value)
Cypress.sinon.match.<matcher name>

用法

正确用法

Cypress.sinon.match.string

错误用法

cy.sinon.match.string // 错误,不能链式调用 'cy'

示例

match.string

这个示例来自配方 Root style。假设应用代码中调用了 setProperty 方法来改变 CSS 变量:

document.querySelector('input[type=color]').addEventListener('change', (e) => {
document.documentElement.style.setProperty(
'--background-color',
e.target.value
)
})

我们可以编写一个测试来确认 setProperty 方法被调用了两个字符串;我们不关心第一个字符串的值,但我们想检查它是否确实是一个字符串。

cy.document()
.its('documentElement.style')
.then((style) => {
cy.spy(style, 'setProperty').as('setColor')
})

cy.get('input[type=color]').invoke('val', '#ff0000').trigger('change')

// 我们不关心 '--background-color' 的具体值
// 但知道它应该是一个字符串
cy.get('@setColor').should(
'have.been.calledWith',
Cypress.sinon.match.string,
'#ff0000'
)

另请参阅