You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JEST中使用OR运算符检查多个匹配值?

问题说明

你当前的写法存在逻辑错误:'past' || 'present' || 'future' 属于JavaScript的或运算,会直接返回第一个真值'past',等效于你只判断data.category匹配past,完全没有覆盖另外两个可选值。

可行解决方案
  • 方案1:使用原生toContain断言(无额外依赖,最推荐)
    将所有允许的返回值存入数组,判断数组包含返回的字段即可,修正后的完整代码如下:
const { randomTense } = require('./src/models/functions');

test('Category exists', () => {
    const data = randomTense()
    console.log(data.category)
    expect(['past', 'present', 'future']).toContain(data.category);
});
  • 方案2:使用正则匹配(适合字符串严格校验场景)
    用正则表达式同时匹配多个可选值,注意添加起止符避免模糊匹配:
test('Category exists', () => {
    const data = randomTense()
    console.log(data.category)
    expect(data.category).toMatch(/^(past|present|future)$/);
});
  • 方案3:使用jest-extended扩展断言
    如果项目已安装jest-extended测试工具集,可以使用语义更清晰的toBeOneOf方法:
expect(data.category).toBeOneOf(['past', 'present', 'future'])

内容的提问来源于stack exchange,提问作者Maurice

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 16:57:08