javascript - 如何使用 Jest 测试同一类中的方法调用?
问题描述
我正在尝试测试类中的函数调用以确保它们被调用,但我似乎无法弄清楚如何使用 Jest 来做到这一点。
自动模拟不起作用,使用模块工厂参数调用 jest.mock 也不起作用。
这是有问题的类,我想测试调用 play() 调用 playSoundFile()。
class SoundPlayer {
constructor() {
this.foo = 'bar';
}
playSoundFile(fileName) {
console.log('Playing sound file ' + fileName);
}
play() {
this.playSoundFile('song.mp3');
}
}
module.exports = SoundPlayer;
这是测试文件:
const SoundPlayer = require('../sound-player');
jest.mock('../sound-player');
it('test', () => {
const soundPlayerConsumer = new SoundPlayer();
const coolSoundFileName = 'song.mp3';
soundPlayerConsumer.play();
const mockPlaySoundFile = SoundPlayer.mock.instances[0].playSoundFile;
expect(mockPlaySoundFile.mock.calls[0][0]).toEqual(coolSoundFileName);
});
mockPlaySoundFile.mock.calls 是空的,因此会出错。
解决方案
我建议你不要嘲笑任何内部方法。相反,您可以模拟任何外部依赖项并调用应该是公共的方法。然后,您针对返回的公共(应该在外部调用)方法运行断言,并检查模拟(模拟的外部依赖项)是否被调用。
在这个特定的例子中,只有console.log
:
console.log = jest.fn();
const soundPlayerConsumer = new SoundPlayer();
soundPlayerConsumer.play();
expect(console.log).toHaveBeenCalledTimes(1);
expect(console.log).toHaveBeenCalledWith('Playing sound file song.mp3');
在更真实的场景中,它可能需要您模拟document
甚至用于jsdom
模拟<audio />
HTML 元素。但是方法是一样的。
推荐阅读
- python - 提取两个多行分隔符之间的内容并检查空值
- php - 用“ ”包装 PHP fputcsv() 生成的 CSV 值
- python - 比较熊猫中的两个日期时间
- angular - 角度,在获得承诺值后无法访问另一个函数中的值
- angular - 如何使用茉莉花和角度测试条件
- flash - 在 Flash AS 2.0 中添加数字
- encryption - 将用户表(使用加密密码)移动到不同的应用程序
- java - JPA Exception 保存父/子
- macos - Macbook Air 在关闭 Android 模拟器时重新启动
- javascript - Jade 代码隐藏/显示基于复选框条件的多核对表