0

I'm fairly new to testing with jest and can't figure out how to test a function that doesn't return anything. This is how I test the function checkSpeed when it returns a value:

function checkSpeed(speed) {
    const speedLimit = 50; 

    if (speed <= speedLimit) {
        return 'Not over the speed limit'; 
    }
    return 'Speed Limit exceeded!');
}

module.exports = checkSpeed

The working test looks like this:

const {expect} = require('@jest/globals');

const checkSpeed = require('./speed');

test ('returns Message according to speed', () => {
    expect(checkSpeed(40)).toBe('Not over the Speed Limit')
    expect(checkSpeed(60)).toBe('Speed Limit exceeded!')
})

But how should I test the function when it doesn't return anything but just displays a message with console.log()? What is considered to be a good practice when testing something like this?

function checkSpeed(speed) {
    const speedLimit = 50; 

    if (speed <= speedLimit) {
        console.log('Not over the speed limit'); 
    }
    console.log('Speed Limit exceeded!');
}

module.exports = checkSpeed
Dantes
  • 3
  • 2
  • A good practice would be to _not_ call console.log directly but instead have a `log` function on a logger and pass `MockLogger` or whatever to the thing creating checkSpeed. An acceptable, easier but worse practice would be to do `console.log = jest.fn())`in a `beforeEach` hook (and restore it in an `afterEach` hook!) and use the mocks api to check `console.log.calls`. – Benjamin Gruenbaum Dec 05 '20 at 17:10
  • Thanks for the comment! Could you please elaborate on what you mean by “have a log function on a logger and pass MockLogger or whatever to the thing creating checkSpeed“, I already went through the different questions/answers before I posted the question here but couldn’t find one that mocked a function that receives arguments and displays a message accordingly. – Dantes Dec 05 '20 at 18:15

0 Answers0