Skip to content
Merged
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
182 changes: 182 additions & 0 deletions __tests__/background-push-handler.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
// Platform.OS and the registered headless tasks live in mocks the tests can read and change.
const mockPlatform = {
OS: 'ios' as 'ios' | 'android',
select: (spec: { [key: string]: unknown }) => spec.default,
};
const mockHeadlessTasks = new Map<
string,
() => (data: unknown) => Promise<void>
>();

jest.mock('react-native', () => ({
Platform: mockPlatform,
AppRegistry: {
registerHeadlessTask: jest.fn(
(key: string, provider: () => (data: unknown) => Promise<void>) => {
mockHeadlessTasks.set(key, provider);
}
),
},
}));
jest.mock('../src/native-logger-listener', () => ({
NativeLoggerListener: { warn: jest.fn() },
}));
jest.mock('../src/specs/modules/NativeCustomerIOMessagingPush', () => {
const nativeModule = {
registerBackgroundPushHandler: jest.fn(),
unregisterBackgroundPushHandler: jest.fn(),
acknowledgeBackgroundPush: jest.fn(),
onBackgroundPushReceived: jest.fn((listener) => {
nativeModule.emit = listener;
return { remove: jest.fn() };
}),
emit: undefined as unknown,
};
return { __esModule: true, default: nativeModule };
});

type NativeMock = {
registerBackgroundPushHandler: jest.Mock;
unregisterBackgroundPushHandler: jest.Mock;
acknowledgeBackgroundPush: jest.Mock;
onBackgroundPushReceived: jest.Mock;
emit?: (event: unknown) => Promise<void>;
};

const push = {
deliveryId: 'delivery-1',
deliveryToken: 'token-1',
data: { account: 'refresh' },
};
const event = { id: 'push-1', push };

// The handler is module state, so each test loads a fresh copy of the module.
const load = () => {
let loaded!: {
pushMessaging: import('../src/customerio-push').CustomerIOPushMessaging;
native: NativeMock;
warn: jest.Mock;
registerHeadlessTask: jest.Mock;
};
jest.isolateModules(() => {
const { CustomerIOPushMessaging } = require('../src/customerio-push');
loaded = {
pushMessaging: new CustomerIOPushMessaging(),
native: require('../src/specs/modules/NativeCustomerIOMessagingPush')
.default,
warn: require('../src/native-logger-listener').NativeLoggerListener.warn,
registerHeadlessTask:
require('react-native').AppRegistry.registerHeadlessTask,
};
});
return loaded;
};

const runTask = (data: unknown) =>
mockHeadlessTasks.get('CustomerIOBackgroundPush')!()(data);

beforeEach(() => {
jest.clearAllMocks();
mockHeadlessTasks.clear();
});

describe('setBackgroundPushHandler on Android', () => {
beforeEach(() => {
mockPlatform.OS = 'android';
});

it('registers the Headless JS task once, before telling native', () => {
const { pushMessaging, native, registerHeadlessTask } = load();

pushMessaging.setBackgroundPushHandler(jest.fn());
pushMessaging.setBackgroundPushHandler(jest.fn());

expect(registerHeadlessTask).toHaveBeenCalledTimes(1);
expect(registerHeadlessTask.mock.invocationCallOrder[0]).toBeLessThan(
native.registerBackgroundPushHandler.mock.invocationCallOrder[0]!
);
expect(native.registerBackgroundPushHandler).toHaveBeenCalledTimes(2);
expect(native.onBackgroundPushReceived).not.toHaveBeenCalled();
});

it('runs the handler, then acknowledges the push', async () => {
const { pushMessaging, native } = load();
const handler = jest.fn(async () => {
expect(native.acknowledgeBackgroundPush).not.toHaveBeenCalled();
});
pushMessaging.setBackgroundPushHandler(handler);

await runTask(event);

expect(handler).toHaveBeenCalledWith(push);
expect(native.acknowledgeBackgroundPush).toHaveBeenCalledWith('push-1');
});

it('acknowledges a push whose handler throws', async () => {
const { pushMessaging, native, warn } = load();
pushMessaging.setBackgroundPushHandler(async () => {
throw new Error('boom');
});

await expect(runTask(event)).resolves.toBeUndefined();

expect(warn).toHaveBeenCalled();
expect(native.acknowledgeBackgroundPush).toHaveBeenCalledWith('push-1');
});

it('stops calling a removed handler but still acknowledges', async () => {
const { pushMessaging, native } = load();
const handler = jest.fn();
pushMessaging.setBackgroundPushHandler(handler).remove();

await runTask(event);

expect(native.unregisterBackgroundPushHandler).toHaveBeenCalledTimes(1);
expect(handler).not.toHaveBeenCalled();
expect(native.acknowledgeBackgroundPush).toHaveBeenCalledWith('push-1');
});

it('keeps a replacement when the old subscription is removed', async () => {
const { pushMessaging, native } = load();
// The same function twice, so only the subscription tells them apart.
const handler = jest.fn();
const first = pushMessaging.setBackgroundPushHandler(handler);
pushMessaging.setBackgroundPushHandler(handler);

first.remove();
await runTask(event);

expect(native.unregisterBackgroundPushHandler).not.toHaveBeenCalled();
expect(handler).toHaveBeenCalledWith(push);
});
});

describe('setBackgroundPushHandler on iOS', () => {
beforeEach(() => {
mockPlatform.OS = 'ios';
});

it('listens for native events before telling native', () => {
const { pushMessaging, native } = load();

pushMessaging.setBackgroundPushHandler(jest.fn());

expect(
native.onBackgroundPushReceived.mock.invocationCallOrder[0]
).toBeLessThan(
native.registerBackgroundPushHandler.mock.invocationCallOrder[0]!
);
expect(mockHeadlessTasks.size).toBe(0);
});

it('runs the handler for a native event, then acknowledges it', async () => {
const { pushMessaging, native } = load();
const handler = jest.fn();
pushMessaging.setBackgroundPushHandler(handler);

await native.emit!(event);

expect(handler).toHaveBeenCalledWith(push);
expect(native.acknowledgeBackgroundPush).toHaveBeenCalledWith('push-1');
});
});
4 changes: 4 additions & 0 deletions android/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,10 @@ dependencies {
// noinspection GradleDynamicVersion
api 'com.facebook.react:react-native:+'
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
// Silent push runs the JavaScript handler in a WorkManager job, which waits without holding a
// WorkManager thread. The native push module already ships both at runtime.
implementation "androidx.work:work-runtime:2.12.0"
implementation "androidx.concurrent:concurrent-futures:1.1.0"

// Jetpack Compose — needed because the Visual Notification Inbox view managers host
// the native `@Composable` inbox components inside a ComposeView.
Expand Down
2 changes: 1 addition & 1 deletion android/gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ customerio.reactnative.kotlinVersion=2.1.20
customerio.reactnative.compileSdkVersion=36
customerio.reactnative.targetSdkVersion=36
customerio.reactnative.minSdkVersion=24
customerio.reactnative.cioSDKVersionAndroid=5.0.3
customerio.reactnative.cioSDKVersionAndroid=5.1.1
7 changes: 7 additions & 0 deletions android/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,13 @@
<meta-data
android:name="io.customer.sdk.android.core.SDK_VERSION"
android:value="@string/customer_io_react_native_sdk_client_version" />

<!-- Registers the silent push callback at process start, so a push that starts a killed
app can reach the JavaScript handler. Inert for apps that don't set one. -->
<provider
android:name="io.customer.reactnative.sdk.messagingpush.ReactBackgroundPushInitProvider"
android:authorities="${applicationId}.customerio.backgroundpush"
android:exported="false" />
</application>

</manifest>
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,22 @@ class NativeMessagingPushModule(

override fun invalidate() {
reactContext.removeActivityEventListener(this)
ReactBackgroundPush.release(reactContext)
super.invalidate()
}

override fun registerBackgroundPushHandler() {
ReactBackgroundPush.register(reactContext)
}

override fun unregisterBackgroundPushHandler() {
ReactBackgroundPush.unregister(reactContext)
}

override fun acknowledgeBackgroundPush(id: String) {
ReactBackgroundPush.acknowledge(id)
}

override fun getPushPermissionStatus(promise: Promise?) {
val result = checkPushPermissionStatus(reactContext).toReactNativeResult
promise?.resolve(result)
Expand Down
Loading
Loading