Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions src/utils/__tests__/addEventListener.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,18 @@ describe('addEventListener', () => {
handler
);
});

// Jest presets often omit AccessibilityInfo (#4373). PaperProvider subscribes
// during mount, so a missing module must not throw.
it('does not throw when the native module is missing', () => {
const subscription = addEventListener(
undefined,
'reduceMotionChanged',
handler
);

expect(() => subscription.remove()).not.toThrow();
});
});

describe('addListener', () => {
Expand Down
38 changes: 29 additions & 9 deletions src/utils/addEventListener.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,39 @@ import type {
EmitterSubscription,
} from 'react-native';

export function addEventListener<
T extends {
addEventListener: (
...args: any
) => NativeEventSubscription | EmitterSubscription | undefined;
} & { removeEventListener?: (...args: any) => void } & {
remove?: (...args: any) => void;
},
>(Module: T, ...rest: Parameters<typeof Module.addEventListener>) {
type EventModule = {
addEventListener: (
...args: any
) => NativeEventSubscription | EmitterSubscription | undefined;
} & { removeEventListener?: (...args: any) => void } & {
remove?: (...args: any) => void;
};

// A missing module is a separate overload so a real module keeps its
// addEventListener overloads. Folding null into T widens every handler (#4373).
export function addEventListener(
Module: null | undefined,
eventName: string,
handler: (...args: any[]) => void
): { remove: () => void };
export function addEventListener<T extends EventModule>(
Module: T,
...rest: Parameters<typeof Module.addEventListener>
): NativeEventSubscription | EmitterSubscription | { remove: () => void };
export function addEventListener(
Module: EventModule | null | undefined,
...rest: any[]
) {
const [eventName, handler] = rest;

let removed = false;

// Jest presets often leave AccessibilityInfo (and similar RN modules)
// undefined. PaperProvider subscribes on mount, so that must not throw (#4373).
if (Module == null || typeof Module.addEventListener !== 'function') {
return { remove() {} };
}

const subscription = Module.addEventListener(eventName, handler) ?? {
remove: () => {
if (removed) {
Expand Down
Loading