1import { renderHook, cleanup } from '@testing-library/react-hooks';
2
3import ExpoScreenCapture from '../ExpoScreenCapture';
4import * as ScreenCapture from '../ScreenCapture';
5
6describe('hooks', () => {
7  afterEach(async () => {
8    await cleanUpTags();
9    await cleanup();
10  });
11
12  const preventScreenCaptureAsyncSpy = jest
13    .spyOn(ExpoScreenCapture, 'preventScreenCapture')
14    .mockResolvedValue();
15  const allowScreenCaptureAsyncSpy = jest
16    .spyOn(ExpoScreenCapture, 'allowScreenCapture')
17    .mockResolvedValue();
18
19  it('calls native methods once if mounted & unmounted', async () => {
20    const hook = renderHook(() => ScreenCapture.usePreventScreenCapture());
21    hook.rerender();
22    expect(preventScreenCaptureAsyncSpy).toHaveBeenCalledTimes(1);
23
24    hook.unmount();
25    expect(allowScreenCaptureAsyncSpy).toHaveBeenCalledTimes(1);
26  });
27
28  it('calls native methods once if mounted & unmounted', async () => {
29    const hook = renderHook(() => ScreenCapture.usePreventScreenCapture());
30    hook.rerender();
31    expect(preventScreenCaptureAsyncSpy).toHaveBeenCalledTimes(1);
32
33    hook.unmount();
34    expect(allowScreenCaptureAsyncSpy).toHaveBeenCalledTimes(1);
35  });
36
37  it('Re runs hook when tag changes', async () => {
38    const hook = renderHook(({ key }) => ScreenCapture.usePreventScreenCapture(key));
39    hook.rerender({ key: 'foo' });
40    hook.rerender({ key: 'bar' });
41
42    expect(preventScreenCaptureAsyncSpy).toHaveBeenCalledTimes(2);
43    expect(allowScreenCaptureAsyncSpy).toHaveBeenCalledTimes(1);
44
45    hook.unmount();
46    // Unmounting results in final allowScreenCapture native method call
47    expect(allowScreenCaptureAsyncSpy).toHaveBeenCalledTimes(2);
48  });
49
50  it('Unmounting one hook when two are active does not re-allow screen capturing', async () => {
51    const hook1 = renderHook(() => ScreenCapture.usePreventScreenCapture());
52    const hook2 = renderHook(({ key }) => ScreenCapture.usePreventScreenCapture(key));
53    hook1.rerender();
54    hook2.rerender({ key: 'foo' });
55    hook2.unmount();
56
57    expect(preventScreenCaptureAsyncSpy).toHaveBeenCalledTimes(2);
58    expect(allowScreenCaptureAsyncSpy).toHaveBeenCalledTimes(0);
59  });
60});
61
62async function cleanUpTags() {
63  // Otherwise, these tags would persist between tests
64  await ScreenCapture.allowScreenCaptureAsync();
65  await ScreenCapture.allowScreenCaptureAsync('foo');
66  await ScreenCapture.allowScreenCaptureAsync('bar');
67}
68