forked from microsoft/rushstack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01-automatic-mock.test.ts
More file actions
42 lines (31 loc) · 1.59 KB
/
01-automatic-mock.test.ts
File metadata and controls
42 lines (31 loc) · 1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
// This example is adapted from the Jest guide here:
// https://jestjs.io/docs/en/es6-class-mocks#automatic-mock
jest.mock('./SoundPlayer'); // SoundPlayer is now a mock constructor
import { SoundPlayer } from './SoundPlayer';
import { SoundPlayerConsumer } from './SoundPlayerConsumer';
beforeEach(() => {
// Clear all instances and calls to constructor and all methods:
jest.mocked(SoundPlayer).mockClear();
});
it('We can check if the consumer called the class constructor', () => {
new SoundPlayerConsumer();
expect(SoundPlayer).toHaveBeenCalledTimes(1);
});
it('We can check if the consumer called a method on the class instance', () => {
// Show that mockClear() is working:
expect(SoundPlayer).not.toHaveBeenCalled();
const soundPlayerConsumer: SoundPlayerConsumer = new SoundPlayerConsumer();
// Constructor should have been called again:
expect(SoundPlayer).toHaveBeenCalledTimes(1);
const coolSoundFileName: string = 'song.mp3';
soundPlayerConsumer.playSomethingCool();
// mock.instances is available with automatic mocks:
const mockSoundPlayerInstance: SoundPlayer = jest.mocked(SoundPlayer).mock.instances[0];
const mockPlaySoundFile = jest.mocked(mockSoundPlayerInstance.playSoundFile);
expect(mockPlaySoundFile.mock.calls[0][0]).toEqual(coolSoundFileName);
// Equivalent to above check:
expect(mockPlaySoundFile).toHaveBeenCalledWith(coolSoundFileName);
expect(mockPlaySoundFile).toHaveBeenCalledTimes(1);
});