-
Notifications
You must be signed in to change notification settings - Fork 1
/
alertSpy.ts
48 lines (37 loc) · 1.3 KB
/
alertSpy.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
37
38
39
40
41
42
43
44
45
46
47
48
import { Alert, AlertButton } from 'react-native';
export interface MockAlertActions {
pressAlertButton(text: string): Promise<void>;
}
export type MockedCall = Readonly<[string, string, ReadonlyArray<AlertButton>]>;
export const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => {});
export const onAlertActions = (): MockAlertActions => {
let dismissedCalls: ReadonlyArray<MockedCall> = [];
return {
pressAlertButton: async (text: string): Promise<void> => {
// @ts-ignore
const unhandledCalls = Alert.alert.mock.calls.slice();
dismissedCalls.forEach((call) => {
const index = unhandledCalls.indexOf(call);
dismissedCalls = dismissedCalls.filter((_, i) => i !== index);
});
if (unhandledCalls.length === 0) {
throw new Error('No pending calls to alert');
}
const mostRecentCall = unhandledCalls[unhandledCalls.length - 1];
const targetButton = mostRecentCall[2].find(
(button: AlertButton) => button.text === text,
);
if (!targetButton) {
throw new Error(`No button with text ${text}`);
}
if (targetButton.onPress) {
await targetButton.onPress();
}
dismissedCalls = [...dismissedCalls, mostRecentCall];
},
};
};
export default {
alertSpy,
onAlertActions,
};