使用Jest示例,所需的类
// sound-player.js
export default class SoundPlayer {
constructor() {
// do something
}
}
和正在测试的课程:
// sound-player-consumer.js
import SoundPlayer from './sound-player';
export default class SoundPlayerConsumer {
playSomethingCool() {
this.soundPlayer = new SoundPlayer();
}
}
我想测试,如果SoundPlayerConsumer
曾经被称为(创建的对象)SoundPlayer
上playSomethingCool()
。我的理解是,它看起来像这样:
import SoundPlayer from './sound-player';
import SoundPlayerConsumer from './sound-player-consumer';
jest.mock('./sound-player');
beforeEach(() => {
SoundPlayer.mockClear();
});
it('check if the consumer is called', () => {
const soundPlayerConsumer = new SoundPlayerConsumer();
soundPlayerConsumer.playSomethingCool();
expect(SoundPlayer).toHaveBeenCalledTimes(1);
});
但是,在我的情况下,我不想导入,./sound-player
因为它具有许多要求和依赖关系,这对我的测试来说是一个过高的选择,因此,我只想手动模拟该类。这是我到目前为止尝试过的:
import SoundPlayerConsumer from './sound-player-consumer';
const SoundPlayer = jest.mock('./sound-player', () => {
return function() {
return {}
}
});
it('check if the consumer is called', () => {
const soundPlayerConsumer = new SoundPlayerConsumer();
soundPlayerConsumer.playSomethingCool();
expect(SoundPlayer).toHaveBeenCalledTimes(1);
});
但这是我得到的结果,我Matcher error: received value must be a mock or spy function
尝试了其他几种变体,但最终总是得到相同的结果。
我已经读过Jest Manual Mocks,但无法完全掌握。
根据Jest docs,mockImplementation
可用于模拟类构造函数。因此,您可以模拟一个类并使用来返回jest函数mockImplementation
。
import SoundPlayerConsumer from './sound-player-consumer';
// must have a 'mock' prefix
const mockSoundPlayer = jest.fn().mockImplementation(() => {
return {}
});
const SoundPlayer = jest.mock('./sound-player', () => {
return mockSoundPlayer
});
it('check if the consumer is called', () => {
const soundPlayerConsumer = new SoundPlayerConsumer();
soundPlayerConsumer.playSomethingCool();
expect(SoundPlayer).toHaveBeenCalledTimes(1);
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句