【发布时间】:2014-12-17 21:35:25
【问题描述】:
我正在尝试编写一个测试,如果输入是字符串或空值,则该测试将通过
在 chai 里面有没有类似的东西
expect(foo).to.be.a('string').or.a('null')
如果不是,那么在编写需要检查多种类型的测试时,最佳实践是什么?
【问题讨论】:
标签: unit-testing chai
我正在尝试编写一个测试,如果输入是字符串或空值,则该测试将通过
在 chai 里面有没有类似的东西
expect(foo).to.be.a('string').or.a('null')
如果不是,那么在编写需要检查多种类型的测试时,最佳实践是什么?
【问题讨论】:
标签: unit-testing chai
这可能是最简单的方法,因为没有 or 关键字。
var str = null;
expect(str).to.satisfy(function(s){
return s === null || typeof s == 'string'
});
【讨论】:
你传递给 chai 的assert 的第一个参数是一个表达式,所以你可以这样做:
assert(assert.isString(foo) || assert.isNull(foo), 'must be a string or null');
【讨论】:
解决方案:
var str = null;
expect(str).to.satisfies(output=>!output); // testcase will pass
var str = '';
expect(str).to.satisfies(output=>!output); // testcase will pass
var str = 'test';
expect(str).to.satisfies(output=>!output); // testcase will fail
【讨论】:
Chai 提供了一个oneOf 方法,它接受一个可能匹配的数组。 OP 的断言,其中类型可以是字符串或空值,因此可以这样编码......
expect(type(foo)).to.be.oneOf(['string', null])
【讨论】:
oneOf 方法是检查值,而不是类型。在这种情况下,它期望 foo 等于 'string' 或 null。
typeof null 是 'object' 而不是 null,所以你的决定是不对的
我会这样写
try {
expect(foo).to.be.a('string');
} catch (e) {
expect(foo, 'expected a string or').to.be.a('null');
}
输出将是
AssertionError: expected a string or: expected 100 to be a null
【讨论】: