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
}
相关推荐
川石课堂软件测试7 小时前
MySQL数据库之DBA命令
数据库·网络协议·mysql·http·单元测试·prometheus·dba
lifewange20 小时前
幂等机制
功能测试·单元测试
=>>漫反射=>>2 天前
单元测试 vs Main方法调试:何时使用哪种方式?
java·spring boot·单元测试
子正2 天前
Pytest单元测试一例:u16采样值格式转换的错误
单元测试·pytest
另寻沧海2 天前
测试中的 AAA 模式与 Given–When–Then 模式详解
c++·单元测试·测试覆盖率
寒月霜华3 天前
java-高级技术(单元测试、反射)
java·开发语言·单元测试·反射
阿杰真不会敲代码3 天前
junit单元测试
junit·单元测试
程序员二黑5 天前
接口测试全流程实战:从工具到架构的深度解析
单元测试·测试·ab测试
步行cgn5 天前
JUnit 单元测试详细使用指南
junit·sqlserver·单元测试
Knight_AL5 天前
Java 单元测试全攻略:JUnit 生命周期、覆盖率提升、自动化框架与 Mock 技术
java·junit·单元测试