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

Jest测试TS报错:SelectOptions.find is not a function问题排查

搞定TypeError: selectOptions.find is not a function这个坑

咱直接说问题根源:你的测试代码传参类型不对!

看你的工具函数checkCaseSensitiveSelectUtil,第二个参数selectOptions明确定义是ISelect[]数组类型,得传一组选项对吧?但你在测试用例里传的selectedOptions是单个对象,不是数组啊!单个JS对象根本没有find方法,这就是测试时报错的核心原因——而实际运行时你肯定是传了正确的数组,所以没出问题。

怎么修复测试代码?

把单个对象包成数组就行,修改后的测试代码如下:

it('should return TRUE if the values are equal', () => {
  // 给对象加个[],转成符合要求的数组类型
  const selectedOptions = [{ label: '*positions', value: '*positions' }];
  expect(checkCaseSensitiveSelectUtil(caseInsensitiveValues, selectedOptions)).toEqual(true);
});

额外提个醒:测试逻辑要匹配函数行为

这里你的测试描述和工具函数的实际逻辑好像有点不匹配:你的工具函数是找不到完全匹配的value时返回true,如果caseInsensitiveValues的value和数组里的选项value完全相等,函数会返回false,你断言toEqual(true)其实是反的。建议调整测试逻辑,让它和函数行为对应上:

测试「存在完全匹配值时返回false」

it('should return FALSE when exact matching value exists', () => {
  const testOption = { label: '*positions', value: '*positions' };
  const selectedOptions = [testOption];
  expect(checkCaseSensitiveSelectUtil(testOption, selectedOptions)).toEqual(false);
});

测试「不存在完全匹配值时返回true」

it('should return TRUE when no exact matching value exists', () => {
  const inputValue = { label: 'Positions', value: 'Positions' };
  const selectedOptions = [{ label: '*positions', value: '*positions' }];
  expect(checkCaseSensitiveSelectUtil(inputValue, selectedOptions)).toEqual(true);
});

这样测试逻辑就清晰多了,不容易搞混~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 09:27:27