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 天前
从本地工具到 MCP:给 Agent 接入独立工具服务,并补齐自动化测试
人工智能·python·功能测试·ai·单元测试·pytest
qq_452396232 天前
第十三篇:《测试策略:单元测试、组件测试、E2E 测试的落地实践》
单元测试
ly76893 天前
前端测试完整指南:从单元测试、组件测试到端到端测试与 CI/CD
前端·ci/cd·单元测试
咖啡星人k3 天前
2026 AI 自动化测试:让 AI 帮你写用例、跑测试、修 Bug(MonkeyCode 云端实战)
人工智能·功能测试·单元测试·测试用例·bug·集成测试
花椒技术4 天前
不是跑通一次 Demo:花椒 QA 怎样把真机 UI 自动化做成回归流程
ios·单元测试·测试
边吃番茄边敲代码4 天前
企业智能助手Agent 安全测试,包含Prompt Injection 和越权工具调用
人工智能·python·功能测试·ai·单元测试·prompt·模块测试
Lost of 程序猿4 天前
ASP.NET Core 测试实战:从单元测试到集成测试的全链路质量保障
单元测试·asp.net·集成测试
hh9505 天前
gent Plan × DeepSeek Harness Agent 单元测试与行为回归框架
人工智能·数据挖掘·回归·单元测试·agent plan·adg成都社区·adg社区
川石课堂软件测试5 天前
自动化测试常见的异常处理
python·jmeter·mysql·docker·容器·单元测试·grafana