如何检查 JEST 中的多个值? (或运算符)

How to check for multiple values in JEST? (OR-operator)

如何检查函数 returns 是否为多个可能值之一?

我当前的测试函数:

const { randomTense } = require('./src/models/functions');

test('Category exists', () => {
    const data = randomTense()
    console.log(data.category)
    expect(data.category).toMatch('past' || 'present' || 'future' );
});

您可以使用如下所示的 'toContain' 方法。

请注意,这不是一个好的测试,因为它不是详尽的或确定性的。如果您的 data.category 有时是别的东西,这可能会随机失败。 想象一下函数 randomTense returns 四个随机排列的字符串:pastpresentfuturethis is a bug。在那种情况下,此测试将通过四次中的三次,并且因为它是随机的,所以不可能(更难)预测它何时会失败。

测试随机函数并不是真正的事情。在这些情况下,您通常做的是将函数分成更小的部分并模拟随机部分。

因此,与其使用一个函数来执行所有操作和随机选择,不如将所有逻辑都去掉,只留下通常只有一行的随机选择。然后你为你的测试模拟该功能并测试 returns options/enums.

的另一个功能
const { randomTense } = require('./src/models/functions');

const POSSIBLE_VALUES = ['past', 'present', 'future'];

test('Category exists', () => {
    const data = randomTense();
    expect(POSSIBLE_VALUES).toContain(data.category);
});