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
}
相关推荐
steel808812 小时前
Spring Boot 整合 log4j2 日志配置教程
spring boot·单元测试·log4j
川石课堂软件测试18 小时前
接口测试需要注意的一些BUG
网络·数据库·python·单元测试·bug·压力测试·tornado
CodeCraft Studio2 天前
Parasoft C/C++嵌入式软件测试解决方案:安全、可靠且符合标准
开发语言·c++·安全·单元测试·代码规范·parasoft·嵌入式软件测试
汽车仪器仪表相关领域2 天前
全工况精准标定 + 智能安全防护,建筑机械防坠生命线:GZCVL T‑II 安全防坠器测试系统实战全解
功能测试·测试工具·安全·单元测试·汽车·压力测试·可用性测试
KevinGuo4572 天前
【前后端开发知识 - 边开发边学习】什么的单元测试、集成测试和E2E测试?
学习·单元测试·集成测试
南昌彭于晏3 天前
springcloud+openFeign单元测试解决初始化循环依赖的问题
spring·spring cloud·单元测试
小璐资源网3 天前
单元测试中应对外部服务依赖的实践指南
单元测试·log4j
深蓝电商API3 天前
爬虫测试:单元测试与集成测试实践
爬虫·单元测试·集成测试
金銀銅鐵4 天前
浅解 JUnit 4 第十八篇:@BeforeClass/@AfterClass 注解如何发挥作用?
junit·单元测试
visual_zhang4 天前
大型 iOS 工程单元测试 — 变更驱动测试与跨模块 Mock
单元测试·代码规范