Skip to content

Commit

Permalink
Call onError if API request fails
Browse files Browse the repository at this point in the history
  • Loading branch information
frankieyan committed Oct 10, 2024
1 parent db9e757 commit 464c3ed
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
7 changes: 4 additions & 3 deletions flagsmith-core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -479,9 +479,10 @@ const Flagsmith = class {
}
if (shouldFetchFlags) {
// We want to resolve init since we have cached flags
this.getFlags().catch((e) => {
this.log("Exception fetching cached logs", e);
});

this.getFlags().catch((error) => {
this.onError?.(error)
})
}
} else {
if (!preventFetch) {
Expand Down
10 changes: 9 additions & 1 deletion test/init.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// Sample test
import { waitFor } from '@testing-library/react';
import { defaultState, environmentID, getFlagsmith, getStateToCheck, identityState } from './test-constants';
import { promises as fs } from 'fs'

Expand Down Expand Up @@ -149,17 +150,24 @@ describe('Flagsmith.init', () => {
})}),
)
});
test('should not reject when the API cannot be reached but the cache is populated', async () => {
test('should not reject but call onError, when the API cannot be reached with the cache populated', async () => {
const onError = jest.fn()
const { flagsmith, initConfig, AsyncStorage } = getFlagsmith({
cacheFlags: true,
fetch: async () => {
return Promise.resolve({ text: () => Promise.resolve('Mocked fetch error'), ok: false, status: 401 });
},
onError,
});
await AsyncStorage.setItem('BULLET_TRAIN_DB', JSON.stringify(defaultState));
await flagsmith.init(initConfig);

expect(getStateToCheck(flagsmith.getState())).toEqual(defaultState);

await waitFor(() => {
expect(onError).toHaveBeenCalledTimes(1)
expect(onError).toHaveBeenCalledWith(new Error('Mocked fetch error'))
})
})
test('should not reject when the API cannot be reached but default flags are set', async () => {
const { flagsmith, initConfig } = getFlagsmith({
Expand Down

0 comments on commit 464c3ed

Please sign in to comment.