Skip to content

Instantly share code, notes, and snippets.

@alexamy
Created January 4, 2023 23:38
Show Gist options
  • Save alexamy/b0fe13745e6beac88b98e87c81f2e15c to your computer and use it in GitHub Desktop.
Save alexamy/b0fe13745e6beac88b98e87c81f2e15c to your computer and use it in GitHub Desktop.
Jest mocking
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