Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用Chai检查对象中的值?_Javascript_Unit Testing_Object_Assertions_Chai - Fatal编程技术网

Javascript 如何使用Chai检查对象中的值?

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”方法 如何测试此功能?具

是否可以使用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;
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','Path
text
是必需的')


谢谢,看起来很漂亮!在这种情况下,最好使用.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"
}