Jestjs 如何测试函数中的函数是否使用正确的参数调用

Jestjs 如何测试函数中的函数是否使用正确的参数调用,jestjs,Jestjs,我得到了这种函数: constplus1=x=>x+1; 常数plus2=x=>x+2; 常量returnPlus1或Plus2=(数字、代码)=> 代码===1?plus1(数字*3):plus2(数字); //如果参数代码为1,则调用参数号为*3的函数plus1, //如果没有,则只需使用param number调用函数plus2 导出默认返回plus1或plus2; 我必须使用jest为该函数创建一个单元测试,我需要测试函数returnplus1或plus2是否根据调用的参数code调用

我得到了这种函数:

constplus1=x=>x+1;
常数plus2=x=>x+2;
常量returnPlus1或Plus2=(数字、代码)=>
代码===1?plus1(数字*3):plus2(数字);
//如果参数代码为1,则调用参数号为*3的函数plus1,
//如果没有,则只需使用param number调用函数plus2
导出默认返回plus1或plus2;
我必须使用jest为该函数创建一个单元测试,我需要测试函数
returnplus1或plus2
是否根据调用的参数code调用了正确的函数
plus1
plus2

    test('function returnPlus1OrPlus2 should call function plus1'()=>{
        expect(returnPlus1OrPlus2(2, 1)).toBe(7);
        //expect(function plus 1 was called with 6)
    })
如何模拟函数
plus1
plus2
,并在测试中编写类似的代码

//expect(使用6调用函数
plus1


如果要模拟或监视函数(
plus1
plus2
),需要确保可以访问它。然后,使用
jest.spyOn
在函数上添加一个间谍,并断言它是否被调用。以下是解决方案:

index.js

constplus1=x=>x+1;
常数plus2=x=>x+2;
常量returnPlus1或Plus2=(数字、代码)=>
代码===1?exports.plus1(编号*3):exports.plus2(编号);
exports.plus1=plus1;
exports.plus2=plus2;
导出默认返回plus1或plus2;
index.spec.js

从“/”导入返回plus1或plus2;
const mymath=require(“./”);
描述(“returnPlus1orPlus2”,()=>{
它(“应该调用plus1”,()=>{
const plus1Spy=jest.spyOn(mymath,“plus1”);
expect(returnPlus1orPlus2(2,1)).toBe(7);
期望(plus1Spy)。与(6)一起调用;
});
它(“应该调用plus2”,()=>{
const plus2Spy=jest.spyOn(mymath,“plus2”);
expect(returnPlus1orPlus2(2,2)).toBe(4);
期望(plus2Spy)。与(2)一起调用;
});
});
100%覆盖率的单元测试结果:

PASS src/stackoverflow/59168766/index.spec.js
返回加1或加2
✓ 应呼叫plus1(5ms)
✓ 应调用plus2(1ms)
----------|----------|----------|----------|----------|-------------------|
文件|%Stmts |%Branch |%Funcs |%Line |未覆盖行|s|
----------|----------|----------|----------|----------|-------------------|
所有文件| 100 | 100 | 100 | 100 ||
index.js | 100 | 100 | 100 | 100 ||
----------|----------|----------|----------|----------|-------------------|
测试套件:1个通过,共1个
测试:2次通过,共2次
快照:共0个
时间:4.109s,估计8s
源代码: