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 小时前
软件测试基础概念
单元测试·pytest
川石课堂软件测试1 天前
技术分享|JMeter接口与性能测试实战
数据库·功能测试·测试工具·jmeter·单元测试·postman·prometheus
汽车仪器仪表相关领域2 天前
Kvaser Leaf Light HS v2 CB:裸卡式CAN接口新标杆,赋能车载与工业集成测试高效升级
服务器·网络·数据库·人工智能·单元测试·自动化·汽车
川石课堂软件测试3 天前
软件测试:典型面试题库
数据库·python·功能测试·mysql·单元测试·grafana·prometheus
汽车仪器仪表相关领域4 天前
Kvaser U100:工业级单通道CAN/CAN FD转USB接口,恶劣环境下的可靠通信桥梁
linux·运维·服务器·人工智能·功能测试·单元测试·可用性测试
芥末的无奈5 天前
Harness Engineering 实战(一):为 fdk-acc 添加单元测试
单元测试·ai编程·harness
发际线向北5 天前
0x03 单元测试与Junit
前端·单元测试
QH139292318806 天前
KEYSIGHT E5071C 端网络分析仪
网络·功能测试·嵌入式硬件·物联网·单元测试·集成测试·模块测试