![](/img/trans.png)
[英]this keyword within a function of an object not returning expected value
[英]Chai's satisfy function is not returning the expected value
所以我有一个像下面这样的对象,我想检查""
和String
。 我的意思是无论是字符串文字还是字符串对象,测试用例都应该通过。
js文件
// * Changing this object to solve the issue is not allowed
const obj = {
a: {
format: "url"
},
b: {
format: String
}
};
如您所见, a's
format
是一个字符串文字,而b's
format
是一个对象。
有线的情况是我很好奇s
参数下有什么样的值(在测试用例中满足)。 因为它使返回false
为b's
format
,但true
为a's
format
。
mocha 测试文件
it('`format` should be a string', () => {
// this returns true
chai.expect(obj.a.format).to.satisfy(function (s) {
return (typeof (s) === 'string') || (s instanceof String);
});
// sadly this returns false
chai.expect(obj.b.format).to.satisfy(function (s) {
return (typeof (s) === 'string') || (s instanceof String);
});
});
测试输出
`format` should be a string:
AssertionError: expected [Function: String] to satisfy [Function]
+ expected - actual
-false
+true
这里有什么问题? 我希望obj.a.format
应该由typeof(s) === 'string'
寻址,而obj.b.format
由s instanceof String
寻址? 而如何让我的测试用例来接受这两种情况下,无论是"string"
或String
?
请记住:“字符串”的类型是字符串,因为它是字符串。 那里没有什么奇怪的。 但是String
的类型是 object,因为它是 String 原型对象,并且原型根据定义不是它自己的实例,所以typeof (s) === 'string'
或s instanceof String
都不是真的。 因此,如果您想检查b
是字符串实例还是实际的String
原型,请使用s === String
,而不是s instanceof String
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.