0

I have a node module I'm trying to write unit tests for. Here's a part of the module:

function _write(level, message) {
    if (level <= _current) {
        message = message || "No message provided.";

        const consoleFn = consoleFunction[level];
        const logFn = console[consoleFn];

        logFn(`${levelPrefix[level]}: ${message}`);
    }
}

When I run the tests including this one:

test('test writing to error log', () => {
    logger.__Rewire__('_write', function (level, message) {
        console.error(`ERROR: ${message}`);
    });
    const spy = jest.spyOn(logger, 'error');
    logger.error('error message');
    expect(spy).toHaveBeenCalledTimes(1);
});

However after running the tests it still looks like the _write function isn't showing up in the coverage results. Is there a way to get jest to understand all the lines of code are getting exercised? Note that "Uncovered Line #s" refers to the exact line numbers of the _write function. I had hoped that by rewiring the function this would make my coverage 100%.

enter image description here

Sarun UK
  • 6,210
  • 7
  • 23
  • 48
Colin
  • 331
  • 3
  • 19

1 Answers1

0

It looks to me like you are mocking the _write function for that test. I don’t expect those lines to get run in this case.

You could write another test that actually uses the _write function.

jens
  • 2,075
  • 10
  • 15
  • So I've actually tried that as well. I added a test where I call logger.error w/o rewiring and % Stmts, % Funcs and % Lines all shoot up to 100. However, % Branch goes up to 27.27 and Uncovered Line #s goes up to 46-98. Why is that? – Colin Oct 09 '20 at 06:14
  • Are you also looking at the generated html report? Hard for me to tell you why thats happening without being able to see all the tests and the full coverage report. – jens Oct 09 '20 at 06:20
  • It might be that your level isn't less than or equal to _current. To enter that branch your test must cause that condition to be true. – jens Oct 09 '20 at 06:22