Skip to content

Commit

Permalink
Add an example for mocking non-default module export class (#9883)
Browse files Browse the repository at this point in the history
  • Loading branch information
ivandotv committed Apr 28, 2020
1 parent 7e37b0f commit 13d6194
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Expand Up @@ -19,6 +19,8 @@

### Chore & Maintenance

- `[docs]` Add an example for mocking non-default export class

### Performance

- `[jest-resolve]` Update `resolve` to a version using native `realpath`, which is faster than the default JS implementation ([#9872](https://github.com/facebook/jest/pull/9872))
Expand Down
16 changes: 16 additions & 0 deletions docs/Es6ClassMocks.md
Expand Up @@ -262,6 +262,22 @@ jest.mock('./sound-player', () => {

This will let us inspect usage of our mocked class, using `SoundPlayer.mock.calls`: `expect(SoundPlayer).toHaveBeenCalled();` or near-equivalent: `expect(SoundPlayer.mock.calls.length).toEqual(1);`

### Mocking non default class exports

If the class is **not** the default export from the module then you need to return an object with the key that is the same as the class export name.

```javascript
import {SoundPlayer} from './sound-player';
jest.mock('./sound-player', () => {
// Works and lets you check for constructor calls:
return {
SoundPlayer: jest.fn().mockImplementation(() => {
return {playSoundFile: () => {}};
}),
};
});
```

### Spying on methods of our class

Our mocked class will need to provide any member functions (`playSoundFile` in the example) that will be called during our tests, or else we'll get an error for calling a function that doesn't exist. But we'll probably want to also spy on calls to those methods, to ensure that they were called with the expected parameters.
Expand Down

0 comments on commit 13d6194

Please sign in to comment.