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
}
相关推荐
不要再敲了3 天前
掌握单元测试的利器:JUnit 注解从入门到精通
junit·单元测试
噔噔噔噔@3 天前
BUG排查流程
单元测试
云动雨颤6 天前
Python单元测试入门:3个核心断言方法,帮你快速定位代码bug
python·单元测试
Suresoft China7 天前
软件测试|STATIC 代码静态验证工具 C/C++ 工具链设置指南
c++·单元测试·静态测试·测试覆盖率·static·代码覆盖率·工具链设置
itppxie8 天前
Simulink中使用Test sequence单元测试
单元测试
泛联新安8 天前
如何根据项目需求选择合适的软件测试工具?iUnit智能单元测试平台提供专业化解决方案
c++·测试工具·单元测试
EndingCoder9 天前
单元测试:Jest 与 Electron 的结合
javascript·electron·单元测试·前端框架
奔跑吧邓邓子10 天前
【Java实战㉖】深入Java单元测试:JUnit 5实战指南
java·junit·单元测试·实战·junit5
川石课堂软件测试10 天前
Oracle 数据库使用事务确保数据的安全
数据库·python·功能测试·docker·oracle·单元测试·prometheus