How do I get everything covered?

67 views Asked by At

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

1

There are 1 answers

3
jens On

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.