gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 23:15:53 25 4
gpt4 key购买 nike

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

我正在尝试创建一个单元测试来检查以确保每个键 "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/)

最佳答案

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

关于javascript - Sinon - 如何检查数组键是否都具有特定值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52795689/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com