Jest - 如何测试调用了 console.error ?

Nic*_*ick 4 javascript unit-testing jestjs

我正在尝试使用 jest/enzyme 编写一个单元测试,该测试测试是否console.error()catch()a 中被调用try/catch,但尝试这样做要么会在测试不成功时导致成功测试,要么会导致“预期的模拟函数被调用,但它没有被称为“错误。

测试功能:

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;
  }
};
Run Code Online (Sandbox Code Playgroud)

所以上面的参数只有一个参数soundName,它是一个字符串,我试图测试当没有参数传入时是否记录了控制台错误。

我最近尝试了下面的方法,这似乎离我们很远,并且错误地返回了通过的测试。

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();
  }
});
Run Code Online (Sandbox Code Playgroud)

jcu*_*bic 12

你的playSound函数永远不会抛出,因为你吞下了异常。

你只需要这个:

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

您还可以检查函数调用的返回值,这将是异常对象。

另外,如果您想检查函数是否抛出,您可以使用

expect(function() { playSound(); }).toThrow();
Run Code Online (Sandbox Code Playgroud)

但这会失败,除非您没有捕获异常或重新抛出。