【问题标题】:Chai deep.include throws Error "Uncaught AssertionError: expected..."Chai deep.include 抛出错误“Uncaught AssertionError:预期......”
【发布时间】:2019-11-07 17:42:51
【问题描述】:

我正在使用 mochachai 进行测试。 res.body.data 是一个对象数组。
当我通过to.include 直接检查一个数组项时,它工作正常,但是当我尝试通过to.deep.include 检查整​​个数组时它失败了。
我卡住了,请帮忙!

res.body.data = [{
  createdAt: 1573147796,
  id: "36d337d4-0184-11ea-acb9-0e4ed9667580",
  message: "Good",
  name: "John Doe",
  rate: 5
}]
//Running test

        expect(res.body.data).to.be.an('array');

        expect(res.body.data[0]).to.include({ //This works fine!
            message: "Good"
        });

        expect(res.body.data).to.deep.include({ //But this trows an error
           message: "Good"
         });
//Uncaught AssertionError: expected [ Array(1) ] to deep include { message: 'Good' }


        done();

【问题讨论】:

    标签: javascript node.js testing mocha.js chai


    【解决方案1】:

    Deep.include 严格检查一个数组,它有成员{message: "Good"}。 测试失败,如果目标数组元素有其他字段 规范有错误的描述。 用于检查数组是否包含包含 { message: "Good" }

    的对象
        expect(res.body.data.some((item) => item.message === "Good")).to.equal(true);
    

    当数组的至少一个元素包含{ message: "Good" }时,测试通过

    【讨论】:

      【解决方案2】:

      我很晚了,但这个答案可能对其他人有帮助。

      所以我也经常在同一个问题上苦苦挣扎,我通过将对象数组转换为字符串然后检查是否包含字符串而不是对象来使其工作。

      expect(JSON.stringify(obj)).to.include(`"message":"Good"`);
      

      查看工作示例here

      【讨论】:

        猜你喜欢
        • 2016-11-24
        • 2023-02-03
        • 1970-01-01
        • 1970-01-01
        • 2017-03-24
        • 2020-04-10
        • 1970-01-01
        • 1970-01-01
        • 2021-09-30
        相关资源
        最近更新 更多