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

216 阅读2分钟

image.png 我们在创建应用程序时经常面临的一个挑战是组合的复杂性。今天,我们将使用我创建的一个方便的助手npm包来列出我们感兴趣的变量的所有可能的排列组合。这对于为每个可能的数据场景生成测试来说特别方便

问题所在

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

下面表示每个变量的可能值。

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

这假设我们对color 的可能值是"red""blue" 、或"green" ,我们对admin 的可能值是truefalse ,我们对mode 的可能值是"light""dark"

我们想用这些变量的每个可能组合来测试我们的应用程序。在这种情况下,有3 x 2 x 2 = 12种组合。我们可以单独写出所有这些测试案例,但这将是一个痛苦。而且,在实际应用中,你很可能最终会出现12以上的组合。

使用Combinate

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

首先,让我们把combinate 安装好。我们可以用npmyarn 来做。

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这样的工具在前台生成故事截图。使用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} />
  ));
});

结论

希望这个小工具可以为你节省一些时间,为测试等事情编写不同的应用程序状态组合很高兴听到你的想法!