【问题标题】:Jest - How to test that console.error is called?开玩笑 - 如何测试调用了 console.error ?
【发布时间】:2019-04-04 11:43:34
【问题描述】:

我正在尝试使用 jest/enzyme 编写一个单元测试,以测试 console.error() 是否已在 try/catchcatch() 中被调用,但尝试这样做会导致测试成功不成功,或“预期的模拟函数已被调用,但没有被调用”错误。

要测试的功能:

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;
  }
};

所以上面有一个参数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();
  }
});

【问题讨论】:

    标签: javascript unit-testing jestjs


    【解决方案1】:

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

    你只需要这个:

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

    你也可以检查函数调用的返回值,它是异常对象。

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

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

    但这会失败,除非你没有捕捉到异常或重新抛出。

    【讨论】:

    • 谢谢。我刚刚尝试过这个并且之前也尝试过类似的方法,但是运行测试总是表明 console.error 永远不会被调用
    • @Nick 我刚刚在本地对其进行了测试,它可以工作,您可能还有其他一些未显示的代码问题。
    猜你喜欢
    • 2017-11-19
    • 2021-03-12
    • 2020-08-16
    • 1970-01-01
    • 1970-01-01
    • 2020-12-16
    • 1970-01-01
    • 2018-08-12
    相关资源
    最近更新 更多