繁体   English   中英

Chai 的满足函数没有返回期望值

[英]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参数下有什么样的值(在测试用例中满足)。 因为它使返回falseb's format ,但truea'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.formats 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM