使用 Combinate 在 JavaScript 中生成所有可能的组合 使用 Combinate 的问题 在测试中使用 结论

2025-06-10

使用 Combinate 在 JavaScript 中生成所有可能的组合

问题

使用合并

在测试中使用

结论

如果您觉得这篇文章有趣,请给它点赞💓、🦄或🔖!

在创建应用程序时,我们经常面临的一个挑战是组合复杂性。今天,我们将使用我创建的一个便捷的 npm 辅助包来列出我们感兴趣的变量的所有可能排列组合。这对于针对所有可能的数据场景生成测试尤其有用!

问题

假设我们有一个应用程序,它具有一些用户设置的color值、一个指示用户是否为的变量admin以及一个lightdark主题mode

以下表示每个变量的可能值:

color = "red" | "blue" | "green"
admin = true | false
mode = "light" | "dark"
Enter fullscreen mode Exit fullscreen mode

这假设color可能值为"red""blue""green",的可能值为admintruefalse的可能值为mode"light""dark"

我们希望用这些变量的每一种可能组合来测试我们的应用。在本例中,共有 3 x 2 x 2 = 12 种组合。我们可以分别写出所有这些测试用例,但那样会很麻烦。而且,在实际应用中,最终可能会出现远超12 种的组合。

使用合并

让我们用combinate我创建的包来解决这个问题!

首先,让我们combinate安装。我们可以使用npm或 来完成yarn

npm i combinate
Enter fullscreen mode Exit fullscreen mode

或者

yarn add combinate
Enter fullscreen mode Exit fullscreen mode

接下来,让我们创建一个对象来代表每个变量的所有可能选项:

const options = {
  color: ["red", "blue", "green"],
  admin: [true, false],
  mode:  ["light", "dark"],
}
Enter fullscreen mode Exit fullscreen mode

最后,我们只需将其传递给我们的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"}
]
*/
Enter fullscreen mode Exit fullscreen mode

在测试中使用

获得所有组合固然很好,但这样做的实际用例是什么?

我使用过的一种方法是使用 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} />
  ));
})
Enter fullscreen mode Exit fullscreen mode

结论

希望这个小工具能帮你节省一些编写不同应用状态组合的时间,比如测试!期待听到你的想法!

鏂囩珷鏉ユ簮锛�https://dev.to/nas5w/generate-all-possible-combinations-in-javascript-using-combinate-1713
PREV
如何使用 AbortController 在 JavaScript 中中止获取请求 使用 AbortController 的简单获取请求 处理取消 关于浏览器兼容性的说明
NEXT
使用 Typescript 在 React 中创建待办事项列表应用程序第 1 部分:引导程序和初始组件第 2 部分:添加动态行为第 3 部分:扩展功能以能够添加项目