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
}
相关推荐
深维AI随笔2 天前
《构建之法》| 第二章个人技术和流程:单元测试不是“可选“,而是“必需“
单元测试·log4j·apache
OPEN-F2 天前
Python进阶教程:单元测试与代码质量
开发语言·python·单元测试
sunshine22 girl4 天前
angular中的测试
前端·单元测试·angular
可遇_不可求5 天前
“像写单元测试一样写性能测试”——k6 完整入门指南
单元测试·性能测试
小小龙学IT5 天前
Google Test(gtest/gmock)开源 C++ 单元测试与 Mock 框架完全指南
c++·单元测试·开源
努力搬砖的咸鱼6 天前
意图理解:让Agent从需求描述自动生成Pytest测试策略
人工智能·python·ai·单元测试·pytest·agent
AI领路人.9 天前
[特殊字符] 用 OpenClaw 实现一个 C++ 复刻版 QuantClaw
websocket·单元测试·discord·rest api·内存占用·c++17
神奇小梵10 天前
《javaweb基础》后端篇————maven补充(用maven单元测试,maven常见问题)
单元测试·maven