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 小时前
pytest_自动化测试4
python·功能测试·单元测试·集成测试·pytest
Lyyaoo.1 天前
Spring Boot日志
spring boot·缓存·单元测试
bug攻城狮1 天前
为什么 Spring Boot 要单元测试?
spring boot·后端·单元测试
liulilittle2 天前
Lua中检测32位序号环绕的方法
junit·单元测试·lua
汽车仪器仪表相关领域3 天前
液力传动精准标定 + 智能换挡控制,动力总成测试新高度:GZCVL T‑IV 变矩器变速箱测试系统实战全解
功能测试·单元测试·汽车·压力测试·可用性测试·安全性测试
程序员小远3 天前
单元测试知识详解
自动化测试·软件测试·python·测试工具·职场和发展·单元测试·测试用例
Warren983 天前
Spring Boot + JUnit5 + Allure 测试报告完整指南
java·spring boot·后端·面试·单元测试·集成测试·模块测试
steel80884 天前
Spring Boot 整合 log4j2 日志配置教程
spring boot·单元测试·log4j
川石课堂软件测试4 天前
接口测试需要注意的一些BUG
网络·数据库·python·单元测试·bug·压力测试·tornado
CodeCraft Studio5 天前
Parasoft C/C++嵌入式软件测试解决方案:安全、可靠且符合标准
开发语言·c++·安全·单元测试·代码规范·parasoft·嵌入式软件测试