【发布时间】:2019-05-14 16:40:04
【问题描述】:
我正在尝试测试类中的函数调用以确保它们被调用,但我似乎无法弄清楚如何使用 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 是空的,因此会出错。
【问题讨论】:
标签: javascript jestjs