Skip to content

Commit 5b62f85

Browse files
committed
27.5
1 parent 20d25cd commit 5b62f85

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

website/versioned_docs/version-27.5/Es6ClassMocks.md

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,76 @@ jest.mock('./sound-player', () => {
236236

237237
This will throw **_TypeError: \_soundPlayer2.default is not a constructor_**, unless the code is transpiled to ES5, e.g. by `@babel/preset-env`. (ES5 doesn't have arrow functions nor classes, so both will be transpiled to plain functions.)
238238

239+
## Mocking a specific method of a class
240+
241+
Lets say that you want to mock or spy the method `playSoundFile` within the class `SoundPlayer`. A simple example:
242+
243+
```javascript
244+
// your jest test file below
245+
import SoundPlayer from './sound-player';
246+
import SoundPlayerConsumer from './sound-player-consumer';
247+
248+
const playSoundFileMock = jest
249+
.spyOn(SoundPlayer.prototype, 'playSoundFile')
250+
.mockImplementation(() => {
251+
console.log('mocked function');
252+
}); // comment this line if just want to "spy"
253+
254+
it('player consumer plays music', () => {
255+
const player = new SoundPlayerConsumer();
256+
player.playSomethingCool();
257+
expect(playSoundFileMock).toHaveBeenCalled();
258+
});
259+
```
260+
261+
### Static, getter and setter methods
262+
263+
Lets imagine our class `SoundPlayer` has a getter method `foo` and a static method `brand`
264+
265+
```javascript
266+
export default class SoundPlayer {
267+
constructor() {
268+
this.foo = 'bar';
269+
}
270+
271+
playSoundFile(fileName) {
272+
console.log('Playing sound file ' + fileName);
273+
}
274+
275+
get foo() {
276+
return 'bar';
277+
}
278+
static brand() {
279+
return 'player-brand';
280+
}
281+
}
282+
```
283+
284+
You can mock/spy them easily, here is an example:
285+
286+
```javascript
287+
// your jest test file below
288+
import SoundPlayer from './sound-player';
289+
import SoundPlayerConsumer from './sound-player-consumer';
290+
291+
const staticMethodMock = jest
292+
.spyOn(SoundPlayer, 'brand')
293+
.mockImplementation(() => 'some-mocked-brand');
294+
295+
const getterMethodMock = jest
296+
.spyOn(SoundPlayer.prototype, 'foo', 'get')
297+
.mockImplementation(() => 'some-mocked-result');
298+
299+
it('custom methods are called', () => {
300+
const player = new SoundPlayer();
301+
const foo = player.foo;
302+
const brand = SoundPlayer.brand();
303+
304+
expect(staticMethodMock).toHaveBeenCalled();
305+
expect(getterMethodMock).toHaveBeenCalled();
306+
});
307+
```
308+
239309
## Keeping track of usage (spying on the mock)
240310

241311
Injecting a test implementation is helpful, but you will probably also want to test whether the class constructor and methods are called with the correct parameters.

0 commit comments

Comments
 (0)