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
}
相关推荐
金銀銅鐵8 小时前
浅解 Junit 4 第四篇:类上的 @Ignore 注解
java·junit·单元测试
金銀銅鐵1 天前
浅解 Junit 4 第二篇: Runner 和 ParentRunner
java·junit·单元测试
流云细水1 天前
Spec实战:需求开发与单元测试如何一一对应?
单元测试
金銀銅鐵1 天前
浅解 Junit 4 第三篇:Suite
junit·单元测试
HashFlag2 天前
单元测试-gomonkey
单元测试·go·gomonkey
HashFlag2 天前
单元测试-httptest
单元测试·go·httptest
HashFlag2 天前
单元测试-go-sqlmock
golang·单元测试·sqlmock
薯条不要番茄酱3 天前
【测试实战篇】“发好论坛”接口自动化测试
python·功能测试·测试工具·单元测试·测试用例·pytest·测试覆盖率
Sandy_Star4 天前
1.5 行政强制和税收保障措施
单元测试
xcLeigh4 天前
AI的提示词专栏:单元测试 Prompt,自动生成测试用例
人工智能·ai·单元测试·prompt·提示词