问题
How do I do an or
test with chai.should?
e.g. something like
total.should.equal(4).or.equal(5)
or
total.should.equal.any(4,5)
What's the right syntax? I couldn't find anything in the documentation
回答1:
Viewing the Chai expect / should documentation, there are several ways to do this test.
Note that you can chain using "and" but apparently not "or" - wish they had this functionality.
- Check whether an object passes a truth test:
.satisfy(method)
@param{ Function }matcher
@param{ String }message_optional_
Asserts that the target passes a given truth test.
Example:
expect(1).to.satisfy(function(num) { return num > 0; });
In your case, to test an "or" condition:
yourVariable.should.satisfy(function (num) {
if ((num === 4) || (num === 5)) {
return true;
} else {
return false;
}
});
- Check whether a number is within a range:
.within(start, finish)
@param{ Number }startlowerbound inclusive
@param{ Number }finishupperbound inclusive
@param{ String }message_optional_
Asserts that the target is within a range.
Example:
expect(7).to.be.within(5,10);
回答2:
Asserts that the target is a member of the given array list. However, it’s often best to assert that the target is equal to its expected value.
expect(1).to.be.oneOf([1, 2, 3]);
expect(1).to.not.be.oneOf([2, 3, 4]);
https://www.chaijs.com/api/bdd/#method_oneof
回答3:
I have a similar problem to write tests to postman. I solved using the following script:
// delete all products, need token with admin role to complete this operation
pm.test("response is ok and should delete all products", function() {
pm.expect(pm.response.code).to.satisfy(function (status) {
if ((status === 204) || (status === 404)) {
return true;
} else {
return false;
}
});
});
回答4:
Because chai assertions throw error you could use try/catch construction:
try {
total.should.equal(4)
} catch (e) {
total.should.equal(5)
}
example of more difficult case:
try {
expect(result).to.have.nested.property('data.' + options.path, null)
} catch (e) {
expect(result).to.have.property('data', null)
}
来源:https://stackoverflow.com/questions/32387293/how-to-do-an-or-in-chai-should