使用 Combinate 在 JavaScript 中生成所有可能的组合
问题
使用合并
在测试中使用
结论
如果您觉得这篇文章有趣,请给它点赞💓、🦄或🔖!
在创建应用程序时,我们经常面临的一个挑战是组合复杂性。今天,我们将使用我创建的一个便捷的 npm 辅助包来列出我们感兴趣的变量的所有可能排列组合。这对于针对所有可能的数据场景生成测试尤其有用!
问题
假设我们有一个应用程序,它具有一些用户设置的color
值、一个指示用户是否为的变量admin
以及一个light
或dark
主题mode
。
以下表示每个变量的可能值:
color = "red" | "blue" | "green"
admin = true | false
mode = "light" | "dark"
这假设color
的可能值为"red"
、"blue"
或"green"
,的可能值为admin
或true
,false
的可能值为mode
和"light"
。"dark"
我们希望用这些变量的每一种可能组合来测试我们的应用。在本例中,共有 3 x 2 x 2 = 12 种组合。我们可以分别写出所有这些测试用例,但那样会很麻烦。而且,在实际应用中,最终可能会出现远超12 种的组合。
使用合并
让我们用combinate
我创建的包来解决这个问题!
首先,让我们combinate
安装。我们可以使用npm
或 来完成yarn
。
npm i combinate
或者
yarn add combinate
接下来,让我们创建一个对象来代表每个变量的所有可能选项:
const options = {
color: ["red", "blue", "green"],
admin: [true, false],
mode: ["light", "dark"],
}
最后,我们只需将其传递给我们的combinate
函数,我们就会得到所有可能组合的数组!让我们看看它的实际效果。
import combinate from "combinate";
const options = {
color: ["red", "blue", "green"],
admin: [true, false],
mode: ["light", "dark"],
}
const combinations = combinate(options);
console.log(combinations);
/*
[
{"admin": true, "color": "red", "mode": "light"},
{"admin": true, "color": "blue", "mode": "light"},
{"admin": true, "color": "green", "mode": "light"},
{"admin": false, "color": "red", "mode": "light"},
{"admin": false, "color": "blue", "mode": "light"},
{"admin": false, "color": "green", "mode": "light"},
{"admin": true, "color": "red", "mode": "dark"},
{"admin": true, "color": "blue", "mode": "dark"},
{"admin": true, "color": "green", "mode": "dark"},
{"admin": false, "color": "red", "mode": "dark"},
{"admin": false, "color": "blue", "mode": "dark"},
{"admin": false, "color": "green", "mode": "dark"}
]
*/
在测试中使用
获得所有组合固然很好,但这样做的实际用例是什么?
我使用过的一种方法是使用 Storybook 之类的工具生成前端 Storyshot。将 Storybook 与 结合使用combinate
,您可以快速为每种可能的组合生成可视化测试。
如果你熟悉 Storybook,那么一个超级简单的例子看起来会是这样的:
// Get all combinations
const options = {
color: ["red", "blue", "green"],
admin: [true, false],
mode: ["light", "dark"],
}
const combinations = combinate(options);
// Create main story section
const navbarStories = storiesOf('Navbar', module);
// Add a story for each combination
combinatons.forEach(({color, admin, mode}) => {
navbarStories.add(`${color} - ${admin} - ${mode}`, () => (
<Navbar color={color} admin={admin} mode={mode} />
));
})
结论
希望这个小工具能帮你节省一些编写不同应用状态组合的时间,比如测试!期待听到你的想法!
鏂囩珷鏉ユ簮锛�https://dev.to/nas5w/generate-all-possible-combinations-in-javascript-using-combinate-1713