diff --git a/CHANGELOG.md b/CHANGELOG.md index f204c42602c7..5e3c4bf5ca58 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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)) diff --git a/docs/Es6ClassMocks.md b/docs/Es6ClassMocks.md index 06209155e304..e541e5c9b334 100644 --- a/docs/Es6ClassMocks.md +++ b/docs/Es6ClassMocks.md @@ -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.