【问题标题】:Testing that an array of objects contains a certain key using Mocha/Chai使用 Mocha/Chai 测试对象数组是否包含某个键
【发布时间】:2020-10-31 08:35:39
【问题描述】:

我正在尝试在一组对象上使用 Mocha 和 Chai 编写一些测试。我想遍历这个数组并返回任何包含error 键的对象。我认为这种事情会很容易,但我遇到了困难。

 [ 
   { fileName: 'font1.ttc', error: 'font_type_not_supported' },
   { fileName: 'font2.ttf', error: 'parse_failed' },
   { fileName: 'font3.tff' } 
 ]

我已经尝试过类似的东西。 expect(testResult).to.have.nested.property('error');

我可能遗漏了一些简单的东西,有人有什么建议吗?

【问题讨论】:

  • 我不知道chai 是否将此作为内置断言。也许只是expect(testResult.some(e => e.error !== undefined)).to.be.true;,假设您正在尝试确定数组中的至少一个对象是否具有所需的键?

标签: testing mocha.js chai


【解决方案1】:

我认为你可以使用节点函数filter 来完成你的工作。

这样的工作:

var array = [
    { fileName: 'font1.ttc', error: 'font_type_not_supported' },
    { fileName: 'font2.ttf', error: 'parse_failed' },
    { fileName: 'font3.tff' }
]
var filter = array.filter(item => item.error != undefined)

通过这种方式,您可以获得存在属性的元素。

但是如果你想比较有多少元素有这个属性,你可以使用length属性。

var count = array.filter(item => item.error != undefined).length
expect(count).gt(0)

如果count变量大于0,意味着至少有一个对象具有该属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2020-08-11
    • 2018-08-09
    • 1970-01-01
    • 2017-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多