【问题标题】:Sinon - How to check that array keys all have particular value?Sinon - 如何检查数组键是否都具有特定值?
【发布时间】:2018-10-13 17:47:54
【问题描述】:

我应该先说我之前从未写过单元测试,所以如果你能对我说清楚,而不是假定你知道高级实践的话。比你。

我正在尝试创建一个单元测试来检查以确保每个键 "x" 具有 "y" 的值。我的 javascript 将 "a""b""c" 传递到 module.exports.handler = async (letter) =>

这会根据参数 "a""b""c" 过滤 JSON,并返回一个包含键/值对的对象数组。

如果传入"a",那么键为"x"的对象数组的值都是"y"

如果"b"作为参数传递,那么键为"x"的对象数组的值是"z"

最后,如果传入参数"c",则具有键"x" 的对象数组具有值"w"

 describe('filtering spec', () => {
   it('should return an array of objects each of which with y as the value', async () => {
     // Makes sure the returned array of objects all have y as the corresponding value for key x
   });

   it('should return an array of objects each of which with z as the value', async () => {
     // Makes sure the returned array of objects all have z as the corresponding value for the key x
   });

   it('should return an array of objects each of which with y as the value', async () => {
     // Makes sure the returned array of objects all have w as the corresponding value for the key x
   });

我猜我最终会以某种方式使用matcher(请参阅https://sinonjs.org/releases/latest/matchers/

【问题讨论】:

  • 你能发布你正在测试的方法吗?

标签: javascript node.js json unit-testing sinon


【解决方案1】:

我建议您使用Array.Filter 方法来查看是否有任何对象具有不需要的值,如果有,那么您的测试应该会失败。

let array = [{x: "y"}, {x: "y"}, {x: "y"}, {x: "b"}]

isCorrect = (array, req) => {
  return (array.filter(v => v.x !== req))
}

console.log(isCorrect(array, "y").length ? "failed" : "passed")

正如 cmets 中所说,Array.some 实际上至少快 18%!

let isSome = (list, req) => {
    return (list.some(v => v.x === req))
}

您也可以使用 Array.includes ...

【讨论】:

  • Array.some 会更快。
猜你喜欢
  • 2018-06-15
  • 1970-01-01
  • 2018-06-14
  • 1970-01-01
  • 2019-12-15
  • 2018-07-02
  • 1970-01-01
  • 2013-03-15
  • 1970-01-01
相关资源
最近更新 更多