官方文档:jest 中文文档
1、模拟某个函数,并返回指定的结果
使用Jest测试JavaScript(Mock篇)
有这样一个需求,mock掉Math.random方法(0(包括)~1之间),使其返回指定的0.1:
jest.spyOn(global.Math, 'random').mockReturnValue(0.1);
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
}