【问题标题】:Should.js not finding object in arrayshould.js 没有在数组中找到对象
【发布时间】:2013-08-01 13:11:47
【问题描述】:

我正在编写测试来验证异步进程写入 mongo 的内容,但我在使用 should.include 来验证是否包含记录时遇到问题。为简化起见,我的投影仅包含一个字段 (ag_status),并且我从 should 收到以下错误:

  1) Agriculture record should return at least one record with ag_status to true:
     Uncaught AssertionError: expected [ { ag_status: true },
  { ag_status: true },
  { ag_status: true },
  { ag_status: true },
  { ag_status: true },
  { ag_status: true } ] to include an object equal to { ag_status: true }

这是调用 should.include 的代码部分。我已经尝试过 chai、chai-fuzzy 和 chai-things,但它们都没有奏效(并且没有给出应有的详细信息)所以我现在被卡住了。非常感谢任何帮助。

    it('Agriculture record should return at least one record with ag_status to true', function(done){
            MobAgriculture.model.find({ time_id: "AYearAgo" }, {_id: 0, ag_status: 1 }, function(err, result) {
                    should.not.exist(err);
                    should.exist(result);
                    result.should.have.length(6);
                    console.log(result);
                    var level2 = { "ag_status" : true };
                    result.should.include(level2);
                    done();
                });

        });

【问题讨论】:

    标签: mocha.js should.js


    【解决方案1】:

    我对 should.js 不是很熟悉,但我认为您应该使用 includeEql,因为您想验证数组中是否存在等于 level2 的对象,而不是那个level2 本身就在那里。来自他们的docs

    包括(对象)

    通过 indexOf() 断言给定的 obj 存在,所以这适用于 实现 indexOf 的字符串、数组或自定义对象。


    includeEql(obj)

    断言与给定 obj 相等的对象存在于数组中:

    【讨论】:

    • 这有帮助,但我仍然收到错误消息。我添加了这个:'var level2 = { ag_status: true }; [{ ag_status: true}, { ag_status: true }].should.includeEql(level2);结果.should.includeEql(level2);'第一个 should 通过,但第二个 should 仍然失败。所以,这与猫鼬如何呈现它有关。但我看不出它有什么问题。有什么想法吗?
    • @frankm 我看到您的示例代码中有一个 console.log 语句,输出是什么样的?如果您从日志中复制输出并用它进行测试,它会起作用吗?
    • 输出是原始帖子的顶部,以“1)农业记录...。”我试图简化 should 测试用例,所以我将猫鼬投影更改为仅输出“{ ag_status: true }”。所以,我的猫鼬输出数组有 6 个元素,每个元素都是“{ ag_status: true }”,我正在搜索的变量是“{ ag_status: true }”。与此同时,我已恢复对 mongoose 结果进行排序并为数组中的每个 x 元素调用“result[x].should.include”,这是目前一个很好的解决方法。
    • 感谢您的帮助!
    • 文档中不再存在(也许现在应该是containEql?)
    猜你喜欢
    • 2020-02-07
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 2015-04-27
    • 2019-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多