如何在玩笑中测试给定的默认参数值?
具有模块的示例:
// 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;
};
答案 0 :(得分:0)
测试用例的每个预期结果都是我们指定的,即我们预先设置了预期结果,测试代码实际返回的结果是否与预期结果一致,如果一致,则测试案例通过,否则失败。代码逻辑有问题。
此外,我们的测试数据和test double应该尽可能简单,这样我们就可以轻松推断出我们期望的结果
例如
calculate.js
:
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.test.js
:
const calc = require('./calculate');
describe('57941350', () => {
it('should return an error if string is undefined', () => {
const actual = calc(undefined);
expect(actual).toBeInstanceOf(Error);
expect(actual.message).toBe('String not defined.');
});
it('should calculate the result with default block size in bits', () => {
const testString = 'a'.repeat(32);
const actual = calc(testString);
expect(actual).toEqual(testString + '\u0000'.repeat(31) + ' ');
});
it('should calculate the result with passed block size in bits', () => {
const testString = 'a';
const actual = calc(testString, 1);
expect(actual).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