gpt4 book ai didi

javascript - 开 Jest - 如何测试 console.error 被调用?

转载 作者:行者123 更新时间:2023-12-02 23:53:49 35 4
gpt4 key购买 nike

我正在尝试使用 jest/enzyme 编写一个单元测试,用于测试 console.error() 是否已在 catch() 中调用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;
}
};

所以上面的代码需要一个参数 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();
}
});

最佳答案

您的 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();

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

关于javascript - 开 Jest - 如何测试 console.error 被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55515179/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com