-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
spyOnConsole.ts
36 lines (31 loc) · 1009 Bytes
/
spyOnConsole.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import { withCleanup } from "./withCleanup.js";
const noOp = () => {};
const restore = (spy: jest.SpyInstance) => spy.mockRestore();
type ConsoleMethod = "log" | "info" | "warn" | "error" | "debug";
type Spies<Keys extends ConsoleMethod[]> = Record<
Keys[number],
jest.SpyInstance<void, any[], any>
>;
/** @internal */
export function spyOnConsole<Keys extends ConsoleMethod[]>(
...spyOn: Keys
): Spies<Keys> & Disposable {
const spies = {} as Spies<Keys>;
for (const key of spyOn) {
// @ts-ignore
spies[key] = jest.spyOn(console, key).mockImplementation(noOp);
}
return withCleanup(spies, (spies) => {
for (const spy of Object.values(spies) as jest.SpyInstance[]) {
restore(spy);
}
});
}
spyOnConsole.takeSnapshots = <Keys extends ConsoleMethod[]>(
...spyOn: Keys
): Spies<Keys> & Disposable =>
withCleanup(spyOnConsole(...spyOn), (spies) => {
for (const spy of Object.values(spies) as jest.SpyInstance[]) {
expect(spy).toMatchSnapshot();
}
});