模拟函数·续2
import SoundPlayer from '../sound-player';import SoundPlayerConsumer from '../sound-player-consumer';jest.mock('../sound-player'); // SoundPlayer is now a mock constructorconst SoundPlayerMock = SoundPlayer as jest.MockedClass<typeof SoundPlayer>;beforeEach(() => { // Clear all instances and calls to constructor and all methods: SoundPlayerMock.mockClear();});it('We can check if the consumer called the class constructor', () => { const soundPlayerConsumer = new SoundPlayerConsumer(); expect(SoundPlayerMock).toHaveBeenCalledTimes(1);});it('We can check if the consumer called a method on the class instance', () => { // Show that mockClear() is working: expect(SoundPlayerMock).not.toHaveBeenCalled(); const soundPlayerConsumer = new SoundPlayerConsumer(); // Constructor should have been called again: expect(SoundPlayerMock).toHaveBeenCalledTimes(1); const coolSoundFileName = 'song.mp3'; soundPlayerConsumer.playSomethingCool(); // mock.instances is available with automatic mocks: const mockSoundPlayerInstance = SoundPlayerMock.mock.instances[0]; // However, it will not allow access to `.mock` in TypeScript as it // is returning `SoundPlayer`. Instead, you can check the calls to a // method like this fully typed: expect(SoundPlayerMock.prototype.playSoundFile.mock.calls[0][0]).toEqual( coolSoundFileName, ); // Equivalent to above check: expect(SoundPlayerMock.prototype.playSoundFile).toHaveBeenCalledWith( coolSoundFileName, ); expect(SoundPlayerMock.prototype.playSoundFile).toHaveBeenCalledTimes(1);}); Instead, you can check the calls to a // method like this fully typed: expect(SoundPlayerMock.prototype.playSoundFile.mock.calls[0][0]).toEqual( coolSoundFileName, ); // Equivalent to above check: expect(SoundPlayerMock.prototype.playSoundFile).toHaveBeenCalledWith( coolSoundFileName, ); expect(SoundPlayerMock.prototype.playSoundFile).toHaveBeenCalledTimes(1);});