Javascript 如何在jest中测试es6默认值

Javascript 如何在jest中测试es6默认值,javascript,unit-testing,jestjs,Javascript,Unit Testing,Jestjs,如何在jest中测试给定的默认参数值 具有该模块的示例: // calculate.js module.exports = (a, b = 3) => { return a + b; } 或者一个更复杂的功能模块 module.exports = (string, blockSizeInBits = 32) => { if (string === undefined) { return new Error('String not defined.')

如何在jest中测试给定的默认参数值

具有该模块的示例:

// calculate.js
module.exports = (a, b = 3) => {
    return a + b;
}
或者一个更复杂的功能模块

module.exports = (string, blockSizeInBits = 32) => {
    if (string === undefined) {
        return new Error('String not defined.');
    }

    const pad  = blockSizeInBits - (string.length % blockSizeInBits);
    const result = string + String.fromCharCode(0).repeat(pad - 1) + String.fromCharCode(pad);

    return result;
};

测试用例的每个预期结果都是由我们指定的,即我们已经预先设置了预期结果,测试代码实际返回的结果是否与预期结果一致,如果一致,则测试用例通过,否则测试用例失败。代码逻辑有问题

此外,我们的测试数据应该尽可能简单,以便我们可以很容易地推断出我们期望的结果

例如

calculate.js

module.exports=(字符串,blockSizeInBits=32)=>{
如果(字符串===未定义){
返回新错误('未定义字符串');
}
常量pad=blockSizeInBits-(string.length%blockSizeInBits);
const result=string+string.fromCharCode(0)。重复(pad-1)+string.fromCharCode(pad);
返回结果;
};
calculate.test.js

const calc=require('./calculate');
描述('57941350',()=>{
它('如果字符串未定义,则应返回错误',()=>{
常量实际值=计算值(未定义);
预期(实际).toBeInstanceOf(错误);
expect(actual.message).toBe('未定义字符串');
});
它('应使用默认块大小(以位为单位)计算结果',()=>{
const testString='a'。重复(32);
常量实际值=计算值(测试字符串);
expect(实际).toEqual(testString+'\u0000'.重复(31)+'';
});
它('应使用以位为单位的传递的块大小计算结果',()=>{
const testString='a';
const actual=calc(testString,1);
expect(实际).toEqual('a\u0001');
});
});
单元测试结果:

 PASS  examples/57941350/calculate.test.js
  57941350
    ✓ should return an error if string is undefined (1 ms)
    ✓ should calculate the result with default block size in bits (1 ms)
    ✓ should calculate the result with passed block size in bits

--------------|---------|----------|---------|---------|-------------------
File          | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
--------------|---------|----------|---------|---------|-------------------
All files     |     100 |      100 |     100 |     100 |                   
 calculate.js |     100 |      100 |     100 |     100 |                   
--------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       3 passed, 3 total
Snapshots:   0 total
Time:        4.849 s

不知道你在问什么?只有一个数字参数的函数调用不会返回该数字+3吗?例如,assert result=input+3?实际示例只是一个简单的函数调用,但我有一点复杂的代码要测试。尽管原理是一样的-测试预期的输入会产生预期的输出(两个参数都通过),然后在缺少rest param参数的情况下进行测试,并确保输出是
32
将产生的结果。不确定困难是什么如果没有办法获取默认参数,我需要更改实际代码的策略,以便能够断言传递给函数的值。谢谢,您不需要检查函数中设置的确切默认参数。您需要检查if-not-provided函数是否可以像显式设置为32一样工作。它可能不会被设置为默认值,而是在内部设置为额外的
。单元测试不是验证代码而是验证行为。哇,答案花了1年零3个月。谢谢