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

使用Jest断言其他模块依赖函数调用失败的问题排查

解决Jest测试中randomNumber未被调用的问题

你的问题出在mock的函数和代码里实际使用的函数没有关联。你在测试里定义了一个独立的randomNumber mock,但Randomize类是直接从Utils模块导入的原始randomNumber函数,所以Jest根本检测不到这个mock的调用。

修复方案:正确mock模块导出的函数

我们需要用Jest的模块mock功能,替换Utils里的randomNumber,让Randomize类使用我们的mock版本:

import { Randomize } from './Randomize'
// 先导入整个Utils模块
import * as Utils from 'Utils'

// Mock Utils模块,保留其他原有函数,只替换randomNumber
jest.mock('Utils', () => ({
  ...jest.requireActual('Utils'),
  randomNumber: jest.fn()
}))

const dataset = [ 'nok', 'nok', 'nok', 'ok', 'nok' ]
const weights = [ 0, 0, 0, 1, 0 ]

describe('operator Randomize#randomPick', () => {
  test('without weights, it calls `randomNumber` with correct range', () => {
    const randomizeOperator = new Randomize({}, [dataset], {})
    randomizeOperator.randomPick(dataset)
    
    // 断言Utils模块里的mock函数被调用
    expect(Utils.randomNumber).toBeCalledWith(0, dataset.length - 1)
  })
})

为什么之前的代码不生效?

你之前创建的const randomNumber = jest.fn()是一个全新的函数实例,和Randomize类从Utils导入的randomNumber完全是两个东西。通过jest.mock,我们告诉Jest:当任何模块导入Utils时,返回的是我们指定的对象,这样Randomize类使用的就会是我们的mock函数了。

额外:补全带权重场景的测试(提升覆盖率)

为了覆盖randomPick的全部分支,你可以添加带权重的测试用例,比如:

test('with weights, it returns correct position based on random weight', () => {
  // 让mock返回固定的随机值,方便测试分支逻辑
  Utils.randomNumber.mockReturnValue(1)
  
  const randomizeOperator = new Randomize({}, [dataset], {})
  const position = randomizeOperator.randomPick(dataset, weights)
  
  expect(position).toBe(3) // 对应权重为1的位置
  expect(Utils.randomNumber).toBeCalledWith(1, 1) // 权重总和是1
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:00:33