user10546475
user10546475

Reputation:

Jest - How to test that console.error is called?

I am trying to write a unit test with jest/enzyme that tests if console.error() has been called in the catch() of a try/catch, but trying to do so either results in a successful test when it should be unsuccessful, or an "Expected mock function to have been called, but it was not called" error.

Function to test:

export const playSound = (soundName, extension = 'wav') => {
  try {
    SoundPlayer.onFinishedPlaying(success => success);
    SoundPlayer.playSoundFile(soundName, extension);
  } catch (err) {
    console.error(`Error playing sound '${soundName}':`, err);
    return err;
  }
};

So the above takes a single argument soundName, which is a string, and I'm trying to test that a console error is logged when no argument is passed in.

I've most-recently tried the below, which seems to be miles off, and wrongfully returns a passed test.

it('fails to play sound with no method arguments', async () => {
  const consoleSpy = jest
    .spyOn(console, 'error')
    .mockImplementation(() => {});
  try {
    playSound();
    expect(consoleSpy).not.toHaveBeenCalled();
  } catch (err) {
    expect(consoleSpy).toHaveBeenCalled();
  }
});

Upvotes: 11

Views: 13251

Answers (1)

jcubic
jcubic

Reputation: 66490

Your playSound function will never throw, because you're swallowing the exception.

you simply need this:

it('fails to play sound with no method arguments', async () => {
  const consoleSpy = jest
    .spyOn(console, 'error')
    .mockImplementation(() => {});
    playSound();
    expect(consoleSpy).toHaveBeenCalled();
});

you can also check return value of the function call, which will be exception object.

Also if you want to check if function throws you can use

expect(function() { playSound(); }).toThrow();

but this will fail, unless you don't catch the exception or rethrow.

Upvotes: 20

Related Questions