Skip to content

fix: BackgroundFlushPolicy doesn't flush the Application Backgrounded… #1049

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
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
Original file line number Diff line number Diff line change
@@ -61,7 +61,7 @@

expect(appStateChangeListener).toBeDefined();

appStateChangeListener!(to);

Check warning on line 64 in packages/core/src/__tests__/internal/handleAppStateChange.test.ts

GitHub Actions / build-and-test

Forbidden non-null assertion
// Since the calls to process lifecycle events are not awaitable we have to await for ticks here
await new Promise(process.nextTick);
await new Promise(process.nextTick);
@@ -163,7 +163,7 @@
// @ts-ignore
expect(client.appState).toBe('background');

expect(mockPlugin.execute).not.toHaveBeenCalled();
expect(mockPlugin.execute).toHaveBeenCalledTimes(1);
});

it('sends an event when unknown => inactive', async () => {
@@ -173,6 +173,6 @@
// @ts-ignore
expect(client.appState).toBe('inactive');

expect(mockPlugin.execute).not.toHaveBeenCalled();
expect(mockPlugin.execute).toHaveBeenCalledTimes(1);
});
});
4 changes: 2 additions & 2 deletions packages/core/src/analytics.ts
Original file line number Diff line number Diff line change
@@ -718,8 +718,8 @@ export class SegmentClient {
void this.process(event);
this.logger.info('TRACK (Application Opened) event saved', event);
} else if (
this.appState === 'active' &&
['inactive', 'background'].includes(nextAppState)
(this.appState === 'active' || this.appState === 'unknown') && // Check if appState is 'active' or 'unknown' //redundant condition need to check without this
['inactive', 'background'].includes(nextAppState) // Check if next app state is 'inactive' or 'background'
) {
const event = createTrackEvent({
event: 'Application Backgrounded',
Original file line number Diff line number Diff line change
@@ -2,6 +2,14 @@ import { AppState, AppStateStatus } from 'react-native';
import { BackgroundFlushPolicy } from '../background-flush-policy';

describe('BackgroundFlushPolicy', () => {
beforeEach(() => {
jest.useFakeTimers(); // Mock timers
});

afterEach(() => {
jest.useRealTimers(); // Restore real timers
});

it('triggers a flush when reaching limit', () => {
let updateCallback = (_val: AppStateStatus) => {
return;
@@ -14,22 +22,29 @@ describe('BackgroundFlushPolicy', () => {
return { remove: jest.fn() };
});

AppState.currentState = 'active';
const policy = new BackgroundFlushPolicy();
policy.start();
const observer = jest.fn();

policy.shouldFlush.onChange(observer);

expect(addSpy).toHaveBeenCalledTimes(1);
updateCallback('inactive');
jest.advanceTimersByTime(2000);

console.log('Observer calls:', observer.mock.calls);
expect(observer).toHaveBeenCalledWith(true);
observer.mockClear();

updateCallback('background');
jest.advanceTimersByTime(2000); // Simulate timer triggering
expect(observer).toHaveBeenCalledWith(true);
observer.mockClear();

updateCallback('active');
jest.advanceTimersByTime(2000);
expect(observer).not.toHaveBeenCalled();

updateCallback('inactive');
expect(observer).toHaveBeenCalledWith(true);
observer.mockClear();
});
});
14 changes: 10 additions & 4 deletions packages/core/src/flushPolicies/background-flush-policy.ts
Original file line number Diff line number Diff line change
@@ -18,18 +18,24 @@ export class BackgroundFlushPolicy extends FlushPolicyBase {
'change',
(nextAppState) => {
if (
this.appState === 'active' &&
['active', 'inactive'].includes(this.appState) &&
['inactive', 'background'].includes(nextAppState)
) {
// When the app goes into the background we will trigger a flush
this.shouldFlush.value = true;
setTimeout(() => {
this.shouldFlush.value = true;
}, 2000);
}
this.appState = nextAppState;
}
);
}

onEvent(_event: SegmentEvent): void {
// Nothing to do
//if ('event' in _event && _event.event === 'Application Backgrounded') {
// setTimeout(() => {
// this.shouldFlush.value = true;
// }, 2000);
// }
}

end(): void {

Unchanged files with check annotations Beta

},
};
const store = new MockSegmentStore({

Check warning on line 176 in packages/core/src/__tests__/internal/checkInstalledVersion.test.ts

GitHub Actions / build-and-test

'store' is already declared in the upper scope on line 22 column 9
context: {
...currentContext,
...injectedContextByPlugins,
it('stamps basic data: timestamp and messageId for pending events when not ready', async () => {
const client = new SegmentClient(clientArgs);
jest.spyOn(client.isReady, 'value', 'get').mockReturnValue(false);
// @ts-ignore

Check warning on line 41 in packages/core/src/__tests__/methods/process.test.ts

GitHub Actions / build-and-test

Do not use "@ts-ignore" because it alters compilation errors
const timeline = client.timeline;
jest.spyOn(timeline, 'process');
};
// While not ready only timestamp and messageId should be defined
// @ts-ignore

Check warning on line 56 in packages/core/src/__tests__/methods/process.test.ts

GitHub Actions / build-and-test

Do not use "@ts-ignore" because it alters compilation errors
const pendingEvents = client.store.pendingEvents.get();
expect(pendingEvents.length).toBe(1);
const pendingEvent = pendingEvents[0];
// When ready it replays events
jest.spyOn(client.isReady, 'value', 'get').mockReturnValue(true);
// @ts-ignore

Check warning on line 69 in packages/core/src/__tests__/methods/process.test.ts

GitHub Actions / build-and-test

Do not use "@ts-ignore" because it alters compilation errors
await client.onReady();
expectedEvent = {
...expectedEvent,
anonymousId: store.userInfo.get().anonymousId,
};
// @ts-ignore

Check warning on line 78 in packages/core/src/__tests__/methods/process.test.ts

GitHub Actions / build-and-test

Do not use "@ts-ignore" because it alters compilation errors
expect(client.store.pendingEvents.get().length).toBe(0);
expect(timeline.process).toHaveBeenCalledWith(
const client = new SegmentClient(clientArgs);
jest.spyOn(client.isReady, 'value', 'get').mockReturnValue(true);
// @ts-ignore

Check warning on line 90 in packages/core/src/__tests__/methods/process.test.ts

GitHub Actions / build-and-test

Do not use "@ts-ignore" because it alters compilation errors
const timeline = client.timeline;
jest.spyOn(timeline, 'process');
anonymousId: store.userInfo.get().anonymousId,
} as SegmentEvent;
// @ts-ignore

Check warning on line 107 in packages/core/src/__tests__/methods/process.test.ts

GitHub Actions / build-and-test

Do not use "@ts-ignore" because it alters compilation errors
const pendingEvents = client.store.pendingEvents.get();
expect(pendingEvents.length).toBe(0);
const client = new SegmentClient(clientArgs);
jest.spyOn(client.isReady, 'value', 'get').mockReturnValue(true);
// @ts-ignore

Check warning on line 120 in packages/core/src/__tests__/methods/process.test.ts

GitHub Actions / build-and-test

Do not use "@ts-ignore" because it alters compilation errors
const timeline = client.timeline;
jest.spyOn(timeline, 'process');
anonymousId: 'foo',
} as SegmentEvent;
// @ts-ignore

Check warning on line 152 in packages/core/src/__tests__/methods/process.test.ts

GitHub Actions / build-and-test

Do not use "@ts-ignore" because it alters compilation errors
const pendingEvents = client.store.pendingEvents.get();
expect(pendingEvents.length).toBe(0);