How to test es6 default values in jest

Tags: , ,



How do you test the given default parameter value in jest?

An example having the module:

// calculate.js
module.exports = (a, b = 3) => {
    return a + b;
}

Or abit more complicated function module.

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;
};

Answer

Each expected result of the test case is specified by us, that is, we have set the expected result in advance, whether the result actually returned by the test code is consistent with the expected result, if it is consistent, the test case passes, otherwise, it fails. There is a problem with the code logic.

Besides, our test data and test double should be as simple as possible, so that we can easily infer the results we expect

E.g.

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('au0001');
  });
});

unit test result:

 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


Source: stackoverflow