如何使用Chai检查对象中是否存在某个值?

9

使用Chai断言库测试值是否包含在某个数组中,是否可能?

例如:

var myObject = {
    a : 1,
    b : 2,
    c : 3
};
var myValue = 2;

我需要做类似这样的事情(但它不起作用):
expect(myObject).values.to.contain(myValue);
//Error: Cannot read property 'to' of undefined

expect(myObject).to.contain(myValue);
//Error: Object #<Object> has no method 'indexOf'

我该如何测试这个功能?

3个回答

18

或者,如果你想检查该属性的值,你可以这样做

expect(myObject).to.have.property('b', myValue);
你不需要为这个检查使用插件。

2
如果对象是位于嵌套中的,例如
{
    "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进行断言,我们可以这样做:

expect(res.body).to.have .property('errors') .property('text') .property('message', '路径 text 是必需的。');


在这种情况下,最好使用.nested,像这样:expect({a: {b: ['x', 'y']}}).to.have.nested.property('a.b[1]'); - Martin Gunnarsson

2

你需要的功能可以通过chai fuzzy插件实现。

var myObject = {
    a : 1,
    b : 2,
    c : 3
};
var myValue = 2;
myObject.should.containOneLike(myValue);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接