js应该在一个属性上链接多个断言

Should.js chaining multiple assertions on a single property

本文关键字:属性 链接 断言 一个 js      更新时间:2023-09-26

我有一个这样的对象:

var obj = {
    "uuid": "60afc3fa-920d-11e5-bd17-b9db323e7d51",
    "type": "candy"
}

我想写一个测试,首先检查对象是否具有属性"uuid",然后检查"uuid"是否为特定长度(36个字符)。

尝试此操作不起作用

obj.should.have.property('uuid').which.should.have.length(36)

它失败了:

Uncaught AssertionError: expected Assertion {
  obj: '60afc3fa-920d-11e5-bd17-b9db323e7d51',
  params: { operator: 'to have property ''uuid''' },
  negate: false } to have property 'length' of 36 (got [Function])

这(实际上无论如何都没有语法意义,因为它适用于父对象,而不是值)

obj.should.have.property('uuid').and.be.length(36)

哪个失败:

Uncaught TypeError: usergridResponse.entity.should.have.property(...).which.should.be.equal.to is not a function

即使这样也不起作用:

obj.should.have.property('uuid').which.equals('60afc3fa-920d-11e5-bd17-b9db323e7d51')

那么,对一个对象的属性进行链式断言的正确方法是什么呢?

我认为这可能是更好的选择:

var session = {
    "uuid": "60afc3fa-920d-11e5-bd17-b9db323e7d51",
    "type": "candy"
};
session.should.have.property('uuid').with.a.lengthOf(36);

或者,如果你想两次选择should,但我认为这不是一个合适的方式(如下所述)。

var session = {
    "uuid": "60afc3fa-920d-11e5-bd17-b9db323e7d51",
    "type": "candy"
};
session.should.have.property('uuid').which.obj.should.have.length(36);

你可以看到他们在这里工作:

https://jsfiddle.net/Lz2zsoks/

.an.of.a.and.be.have.with.is.which只是什么都不做的链接器。

更新

作为对@denbardadym的回应,我将尝试解释为什么不应该使用should两次:

  • 你不会在自然语言中使用两次,所以最好不要在测试中使用
  • Should.js不打算以这种方式使用。您在库文档中找不到任何这种用法的示例

第一个语句失败,因为您调用.should两次-第二次在断言时断言,它应该是:

obj.should.have.property('uuid').which.have.length(36)

(错误消息字面上说,Assertion {...}没有属性长度)

第二句话不适合我:

obj.should.have.property('uuid').and.be.length(36)

(您的错误消息看起来并不是断言失败)

最后一条语句——没有.equals断言——应该是.equal。因为"0320a79a-920d-11e5-9b7a-057d4ca344ba" !== "60afc3fa-920d-11e5-bd17-b9db323e7d51"

希望能有所帮助。