gpt4 book ai didi

javascript - Jest 测试将返回值匹配为哈希的子集 - 无需调用该函数两次?

转载 作者:行者123 更新时间:2023-12-01 02:54:52 24 4
gpt4 key购买 nike

我想将函数返回值的数据结构与更大的结构进行匹配(即返回的结构针对更完整的哈希进行“验证”)。我有一个使用 toHaveProperty 的工作测试,但我不想在测试中针对这个特定问题定义我的对象结构。

我真正想要的是让我测试包含在更大哈希中的结构(而不​​是值)并找到不调用该函数两次的方法:

// ** this would fail if a property value is different **
test('thing returns something matching the structure within types', () => {
expect(thing()).toBeDefined(
expect(types).toMatchObject(thing())
);
});

结构如下:

var types = {
changeSheet:{
command: ["s", "sheet"],
options: [],
required: [],
sheet_option: true,
},
checkIn:{
command: ["in", "i"],
options: ["-a", "--at"],
required: [],
sheet_option: false,
},
checkOut:{
command: ["out", "o"],
options: ["-a", "--at"],
required: [],
sheet_option: true,
}
};

这是我要测试的功能:

function thing() {
return {changeSheet: {
command: ["s", "sheet"],
options: [],
required: [],
sheet_option: false,
}};
}

请注意,changeSheet.sheet_option 与返回值与“类型”散列不同。是否有一个 Jest 匹配机制可以检查我的结构并忽略这些值,或者我是否坚持使用 toHaveProperty()?

最佳答案

您可以使用 Jest 的 expect 匹配工具:http://facebook.github.io/jest/docs/en/expect.html#content

expect(thing()).toMatchObject({
changeSheet: {
command: expect.arrayContaining([
expect.any(String),
expect.any(String)
]),
options: expect.any(Array),
required: expect.any(Array),
sheet_option: expect.any(Boolean)
}
});

也就是说,您在这里测试的只是结构/类型,通过使用 TypeScript 或 Flow 等静态类型检查器可能会更好地完成。

关于javascript - Jest 测试将返回值匹配为哈希的子集 - 无需调用该函数两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46758406/

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