您可以使用自定义匹配器,这是一个具有任意复杂度并返回 true 或 false 的函数。
function checkMyProp(obj) {
const myProp = obj['myProp'];
return myProp === undefined ||
(myProp !== undefined && typeof myProp === 'string' && myProp === '');
}
it('succeeds when myProp does not exist', () => {
const obj={ a:1, b:2, c:3 }
expect(obj).to.satisfy(checkMyProp, 'myProp meets the criteria');
})
it('succeeds when myProp is an empty string', () => {
const obj={ a:1, b:2, c:3, myProp: '' }
expect(obj).to.satisfy(checkMyProp, 'myProp meets the criteria');
})
it('fails when myProp is a string but not empty', () => {
const obj={ a:1, b:2, c:3, myProp: 'myValue' }
expect(obj).to.satisfy(checkMyProp, 'myProp meets the criteria');
})
it('fails when myProp is a number', () => {
const obj={ a:1, b:2, c:3, myProp: 4 }
expect(obj).to.satisfy(checkMyProp, 'myProp meets the criteria');
})
如果要在测试中配置匹配器,使用高阶函数(返回函数的函数)
function matcherFor(prop) {
return (obj) => {
const myProp = obj[prop];
return myProp === undefined ||
(myProp !== undefined && typeof myProp === 'string' && myProp === '');
}
}
it('succeeds when myProp does not exist', () => {
const obj={ a:1, b:2, c:3 }
expect(obj).to.satisfy(matcherFor('myProp'), 'myProp meets the criteria');
})
或作为单线(=== 运算符中隐含 typeof 检查)
const matcherFor = (prop) => (obj) => obj[prop] === undefined || obj[prop] === '';
您可以使用与 .should() 相同的语法作为命令中的验证步骤
it('as a validation step in a test chain', () => {
const obj={ a:1, b:2, c:3 }
cy.wrap(obj)
.should('satisfy', matcherFor('myProp'), 'myProp meets the criteria')
.then(obj => {
// process object
})
})