Unit testing 如何编写一个测试来检查chai中的多种类型

Unit testing 如何编写一个测试来检查chai中的多种类型,unit-testing,chai,Unit Testing,Chai,我正在尝试编写一个测试,如果输入是字符串或空值,该测试将通过 在柴有类似的东西吗 expect(foo).to.be.a('string').or.a('null') 如果不是,那么在编写需要检查多种类型的测试时,最佳做法是什么?传递到chai的assert中的第一个参数是一个表达式,因此可以执行以下操作: assert(assert.isString(foo)| assert.isNull(foo),'必须是字符串或null')这可能是最简单的方法,因为没有或关键字 var str = nu

我正在尝试编写一个测试,如果输入是字符串或空值,该测试将通过

在柴有类似的东西吗

expect(foo).to.be.a('string').or.a('null')

如果不是,那么在编写需要检查多种类型的测试时,最佳做法是什么?

传递到chai的
assert
中的第一个参数是一个表达式,因此可以执行以下操作:


assert(assert.isString(foo)| assert.isNull(foo),'必须是字符串或null')

这可能是最简单的方法,因为没有
关键字

var str = null;

expect(str).to.satisfy(function(s){
    return s === null || typeof s == 'string'
});
Chai提供了一个方法,该方法接受一系列可能的匹配项。 OP的断言,其中类型可以是字符串或null,因此可以这样编码

expect(type(foo)).to.be.oneOf(['string', 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

assert抛出一个错误,但本例假设它返回一个布尔值。
方法之一是检查值,而不是类型。在本例中,它期望
foo
等于'string'或null。是的,你说得很对。我已更正代码,使其仅针对类型(值)而不是值进行断言。该模块也是必需的。@WillP,
typeof null
是“object”而不是null,因此您的决定不正确