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
}
相关推荐
記億揺晃着的那天2 天前
MyBatis-Plus 单元测试中 Lambda Mock 的坑与解决
单元测试·log4j·mybatis
CeshirenTester2 天前
Playwright元素定位详解:8种定位策略实战指南
人工智能·功能测试·程序人生·单元测试·自动化
行走的陀螺仪3 天前
Vue3 项目单元测试全指南:价值、Vitest 落地与提效方案
开发语言·前端·单元测试·html5·vitest
fzm52983 天前
C语言单元测试在嵌入式软件开发中的作用及专业工具的应用
自动化测试·单元测试·汽车·嵌入式·白盒测试
川石课堂软件测试3 天前
Mysql中触发器使用详详详详详解~
数据库·redis·功能测试·mysql·oracle·单元测试·自动化
程序员汤圆3 天前
软件测试面试题总结【含答案】
测试工具·单元测试·测试用例
卓码软件测评4 天前
第三方软件CMA/CNAS测评机构:【Apifox的自定义加密和签名的安全测试技巧】
测试工具·ci/cd·单元测试·测试用例·压力测试
IMPYLH4 天前
Lua 的 Debug(调试) 模块
开发语言·笔记·python·单元测试·lua·fastapi
测试开发Kevin4 天前
超级实用!汇总pytest中那些常用的参数
单元测试·pytest
charlie1145141915 天前
编写INI Parser 测试完整指南 - 从零开始
开发语言·c++·笔记·学习·算法·单元测试·测试