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
}
相关推荐
川石课堂软件测试17 小时前
安全测试|服务器安全加固方法
服务器·功能测试·测试工具·jmeter·mysql·web安全·单元测试
测试修炼手册1 天前
[测试技术] GoogleTest 入门与实战:单元测试、参数化与 Mock
单元测试
不平衡的叉叉树2 天前
Springboot+Mockito简单使用单元测试
java·spring boot·单元测试
大师兄66683 天前
HarmonyOS7 单元测试:从 @Test 到覆盖率
单元测试·覆盖率·harmonyos7
HokKeung5 天前
Go 项目难测试,问题通常出在代码结构
单元测试·go
博观而约取厚积而薄发6 天前
Pytest 从入门到精通,一篇就够(超详细实战教程)
python·测试工具·单元测试·自动化·pytest
gis开发之家6 天前
《Vue3 从入门到大神29篇》单元测试与 E2E 测试 —— 保障 Vue3 项目的质量
前端·javascript·vue.js·单元测试·前端框架·vue3
ysu_03146 天前
06 | 200个单元测试C项目也能TDD
c语言·单元测试·tdd