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
}
相关推荐
金銀銅鐵37 分钟前
浅解 JUnit 4 第十一篇:@Before 注解和 @After 注解如何发挥作用?
junit·单元测试
金銀銅鐵1 天前
浅解 JUnit 4 第十篇:方法上的 @Ignore 注解
junit·单元测试
阿狸猿3 天前
单元测试中静态测试、动态测试及白盒测试、回归测试实践
单元测试·软考
Max_uuc3 天前
【工程心法】从“在板盲调”到“云端验证”:嵌入式单元测试与 TDD 的工程化革命
单元测试·tdd
feathered-feathered4 天前
测试实战【用例设计】自己写的项目+功能测试(1)
java·服务器·后端·功能测试·jmeter·单元测试·压力测试
测试渣4 天前
持续集成中的自动化测试框架优化实战指南
python·ci/cd·单元测试·自动化·pytest
minh_coo4 天前
Spring单元测试之反射利器:ReflectionTestUtils
java·后端·spring·单元测试·intellij-idea
金銀銅鐵5 天前
浅解 JUnit 4 第九篇:JUnitCore (下)
junit·单元测试
A懿轩A5 天前
【Maven 构建工具】Maven + JUnit5 单元测试实战:测试级别、注解、断言与 Maven test 阶段
java·单元测试·maven