【问题标题】:How to check the value is in object with Chai?如何使用 Chai 检查值是否在对象中?
【发布时间】:2013-05-03 10:12:08
【问题描述】:

是否可以使用 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'

我该如何测试这个?

【问题讨论】:

    标签: javascript unit-testing object assertions chai


    【解决方案1】:

    或者,如果您想检查该值以及您可以执行的属性

    expect(myObject).to.have.property('b', myValue);
    

    此检查不需要插件。

    【讨论】:

      【解决方案2】:

      chai fuzzy plugin 具有您需要的功能。

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

      【讨论】:

      • 谢谢,它看起来棒极了!
      【解决方案3】:

      如果对象是位嵌套的,比如

      {
          "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做一个断言,我们可以这样做

      期望(res.body).to.have .property('错误') .property('文本') .property('message', '路径text是必需的。');

      【讨论】:

      • 在这种情况下,最好使用 .nested,如下所示:expect({a: {b: ['x', 'y']}}).to.have.nested.property ('a.b[1]');
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多