Jest单元测试相关

官方文档:jest 中文文档

1、模拟某个函数,并返回指定的结果

使用Jest测试JavaScript(Mock篇)

有这样一个需求,mock掉Math.random方法(0(包括)~1之间),使其返回指定的0.1:

javascript 复制代码
jest.spyOn(global.Math, 'random').mockReturnValue(0.1);
javascript 复制代码
test('when rate is 0~1, will not be sampled randomly', () => {
  jest.spyOn(global.Math, 'random').mockReturnValue(0.1);
  const result = sampler.shouldSample({
    ...SAMPLE_OPTIONS,
    options: { rate: 0.5 },
  });
  expect(result.decision).toEqual(true);
});

public shouldSample(config: Config): api.SamplingResult {
  const { rateDaily, rateCampaign } = this._options;
  const { options } = config;
  const rate = normalize(
    typeof options?.rate === 'number'
      ? options.rate
      : getCurrentRate(rateDaily, rateCampaign)
  );
  return { decision: rate !== NOT_SAMPLED_RATE && Math.random() < rate }; // 希望这里能指定返回true
}
相关推荐
卓码软件测评18 小时前
软件信创测试和软件首版次认定机构【使用Postman的Pre-request Script动态处理数据】
测试工具·ci/cd·性能优化·单元测试·测试用例
汽车仪器仪表相关领域1 天前
全组分精准捕获,台架研发中枢:MEXA-ONE发动机尾气测量装置项目实战全景
大数据·人工智能·功能测试·单元测试·压力测试·可用性测试
软件测试君1 天前
2025年10款王炸AI测试工具,你用过几款?
自动化测试·软件测试·人工智能·深度学习·测试工具·单元测试·ai测试工具
2401_861277552 天前
事件驱动架构软件测试要点是什么
单元测试·测试用例
移幻漂流2 天前
Lua的现状与机遇:技术生态全景及高潜力领域分析
junit·单元测试·lua
开五档的蒙奇2 天前
【单元测试】Junit5 + Mockito
单元测试
程序员雷叔3 天前
在postman设置请求里带动态token,看看这两种方法!
selenium·测试工具·单元测试·测试用例·pytest·lua·postman
IMPYLH4 天前
Lua 的 String(字符串) 模块
开发语言·笔记·单元测试·lua
卓码软件测评4 天前
第三方软件确认测试机构【性能测试中内存泄漏的迹象:如何利用LoadRunner监控和发现 】
测试工具·ci/cd·性能优化·单元测试·测试用例
移幻漂流4 天前
Lua关键字全解析:从基础到精通的语义指南
junit·单元测试·lua