Javascript 如何使用Chai检查对象中的值?
是否可以使用CAI断言库测试包含在特定数组中的值 例如:Javascript 如何使用Chai检查对象中的值?,javascript,unit-testing,object,assertions,chai,Javascript,Unit Testing,Object,Assertions,Chai,是否可以使用CAI断言库测试包含在特定数组中的值 例如: var myObject = { a : 1, b : 2, c : 3 }; var myValue = 2; 我需要这样做(但它不起作用): expect(myObject).values.to.contain(myValue); //错误:无法读取未定义的属性“to” expect(myObject).to.contain(myValue); //错误:对象#没有“indexOf”方法 如何测试此功能?具
var myObject = {
a : 1,
b : 2,
c : 3
};
var myValue = 2;
我需要这样做(但它不起作用):
expect(myObject).values.to.contain(myValue);
//错误:无法读取未定义的属性“to”
expect(myObject).to.contain(myValue);
//错误:对象#没有“indexOf”方法
如何测试此功能?具有您需要的功能
var myObject = {
a : 1,
b : 2,
c : 3
};
var myValue = 2;
myObject.should.containOneLike(myValue);
或者,如果要检查值和属性,可以执行以下操作
expect(myObject).to.have.property('b', myValue);
此检查不需要插件。如果对象是位嵌套的,如
{
"errors": {
"text": {
"message": "Path `text` is required.",
"name": "ValidatorError",
"properties": {
"message": "Path `{PATH}` is required.",
"type": "required",
"path": "text",
"value": ""
},
"kind": "required",
"path": "text",
"value": "",
"$isValidatorError": true
}
},
"_message": "todos validation failed",
"message": "todos validation failed: text: Path `text` is required.",
"name": "ValidationError"
}
然后对errors.text.message执行断言,我们可以像
期望
.property(“错误”)
.property(“文本”)
.property('message','Pathtext
是必需的')
谢谢,看起来很漂亮!在这种情况下,最好使用.nested,如下所示:expect({a:{b:['x',y']}).to.have.nested.property('a.b[1]');
{
"errors": {
"text": {
"message": "Path `text` is required.",
"name": "ValidatorError",
"properties": {
"message": "Path `{PATH}` is required.",
"type": "required",
"path": "text",
"value": ""
},
"kind": "required",
"path": "text",
"value": "",
"$isValidatorError": true
}
},
"_message": "todos validation failed",
"message": "todos validation failed: text: Path `text` is required.",
"name": "ValidationError"
}