-
Notifications
You must be signed in to change notification settings - Fork 10
/
testUtils.tsx
99 lines (79 loc) · 2.61 KB
/
testUtils.tsx
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import React from 'react';
import { mocked } from 'ts-jest/utils';
import { render } from '@testing-library/react';
import { collect, internals } from '..';
import * as paths from '../src/shared/paths';
export const renderStrict = (children: React.ReactNode) => {
return render(<React.StrictMode>{children}</React.StrictMode>);
};
// Use collectAndRenderStrict instead of this if you don't need to count
// the number of renders
export const collectAndRender = (Comp: React.ComponentType<any>) => {
const CollectedComp = collect(Comp);
return render(<CollectedComp />);
};
export const collectAndRenderStrict = (Comp: React.ComponentType<any>) => {
const CollectedComp = collect(Comp);
return renderStrict(<CollectedComp />);
};
export const propPathChanges = (handleChangeMock: jest.Mock) =>
handleChangeMock.mock.calls.map((call) => call[0].changedProps[0]);
export const getAllListeners = () =>
Array.from(internals.listeners.keys()).map(paths.internalToUser);
type ConsoleMethod = jest.FunctionPropertyNames<Required<typeof console>>;
type ConsoleMockFunc = {
(func: () => void): string | string[];
};
/**
* Run some code with the console mocked.
*/
const withMockedConsole = (
func: () => void,
method: ConsoleMethod
): string | string[] => {
jest.spyOn(console, method);
const mockedConsole = mocked(window.console[method], true);
mockedConsole.mockImplementation(() => {});
func();
const consoleOutput =
mockedConsole.mock.calls.length === 1
? mockedConsole.mock.calls[0][0]
: mockedConsole.mock.calls.map((args: [string]) => args[0]);
mockedConsole.mockRestore();
return consoleOutput;
};
export const withMockedConsoleInfo: ConsoleMockFunc = (func) =>
withMockedConsole(func, 'info');
export const withMockedConsoleWarn: ConsoleMockFunc = (func) =>
withMockedConsole(func, 'warn');
export const expectToLogError: ConsoleMockFunc = (func) => {
const consoleError = withMockedConsole(func, 'error');
expect(consoleError).not.toBeUndefined();
return consoleError;
};
export type TaskType = {
id: number;
name: string;
done?: boolean;
};
declare module '..' {
// Add a few things used in the tests
interface Store {
tasks?: TaskType[];
// And anything else...
[key: string]: any;
}
}
// TODO: Delete me when this is merged:
// https://github.com/DefinitelyTyped/DefinitelyTyped/pull/43102
declare module '@testing-library/dom' {
export function waitFor(
callback: () => void,
options?: {
container?: HTMLElement;
timeout?: number;
interval?: number;
mutationObserverOptions?: MutationObserverInit;
}
): Promise<void>;
}