[英]How to test es6 default values in jest
你如何在 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 = (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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.