Created
January 4, 2023 23:38
-
-
Save alexamy/b0fe13745e6beac88b98e87c81f2e15c to your computer and use it in GitHub Desktop.
Jest mocking
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { nanoid } from 'nanoid/non-secure'; | |
import { Autolog } from '../autolog'; | |
jest.mock('nanoid/non-secure'); | |
jest.mock('../autolog', () => { | |
const actual = jest.requireActual('../autolog'); | |
return { | |
__esModule: true, | |
...actual, | |
Autolog: jest.fn().mockImplementation(actual.Autolog), | |
}; | |
}); | |
// nanoid example | |
beforeEach(() => { | |
const mockNanoid = nanoid as jest.MockedFunction<typeof nanoid>; | |
mockNanoid.mockReturnValueOnce('testid'); | |
// now something in depths of code nanoid will return 'testid' | |
}); | |
// autolog example | |
beforeEach(() => { | |
Autolog.mockClear(); | |
}); | |
it('provides autolog', () => { | |
expect(Autolog).toHaveBeenCalledTimes(1); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment