Sinon - 如何检查数组键是否都具有特定值?

Sinon - How to check that array keys all have particular value?

我应该先说我以前 从未 写过单元测试,所以如果你能对我说清楚并且不要假定我了解高级实践。比你。

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

这会根据参数 "a""b""c" 和 [=52= 过滤 JSON ] 具有 key/value 对的对象数组。

如果传入"a",则key为"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/

我建议您使用 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")

如评论中所述,Array.some 实际上至少快 18%!

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

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