Something went wrong. Try again.
Mirror — see github.com/blacksky-algorithms/blacksky.community
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437import {Alert} from 'react-native'import { checkForUpdateAsync, fetchUpdateAsync, reloadAsync, setExtraParamAsync, setUpdateURLAndRequestHeadersOverride, UpdateCheckResultNotAvailableReason, useUpdates,} from 'expo-updates'import {act, renderHook, waitFor} from '@testing-library/react-native'
import {logger} from '#/logger'import {APP_VERSION} from '#/env'import {device} from '#/storage'import { useApplyPullRequestOTAUpdate, useOTAUpdateRecovery,} from './useOTAUpdates'
jest.mock('expo-updates', () => ({ checkForUpdateAsync: jest.fn(), fetchUpdateAsync: jest.fn(), isEnabled: true, reloadAsync: jest.fn(), setExtraParamAsync: jest.fn(), setUpdateURLAndRequestHeadersOverride: jest.fn(), UpdateCheckResultNotAvailableReason: { NO_UPDATE_AVAILABLE_ON_SERVER: 'noUpdateAvailableOnServer', UPDATE_PREVIOUSLY_FAILED: 'updatePreviouslyFailed', }, useUpdates: jest.fn(),}))
jest.mock('expo-linking', () => ({ getLinkingURL: jest.fn(() => null),}))
jest.mock('#/logger', () => ({ logger: { debug: jest.fn(), error: jest.fn(), },}))
jest.mock('#/storage', () => ({ device: { get: jest.fn(), remove: jest.fn(), set: jest.fn(), },}))
jest.mock('#/alf', () => ({ useTheme: jest.fn().mockImplementation(() => ({ scheme: 'light', })),}))
/** * `channel` here is the build-time constant baked into the native build, not the * channel of the running bundle. `channel` is passed as the manifest metadata * channel our update server stamps into every published update - omit it to * simulate an embedded launch, which has no server manifest. */function mockCurrentlyRunning({ buildChannel = 'testflight', channel, updateId = 'current-update',}: { buildChannel?: string channel?: string updateId?: string} = {}) { const currentlyRunning = { channel: buildChannel, emergencyLaunchReason: null, isEmbeddedLaunch: !channel, isEmergencyLaunch: false, updateId, manifest: channel ? {id: updateId, metadata: {channel}} : undefined, } jest.mocked(useUpdates).mockReturnValue({ currentlyRunning, } as ReturnType<typeof useUpdates>) return currentlyRunning}
const currentUpdate = {updateId: 'current-update'}
beforeEach(() => { jest.clearAllMocks() mockCurrentlyRunning() jest.mocked(setExtraParamAsync).mockResolvedValue(undefined) jest.mocked(reloadAsync).mockResolvedValue(undefined) jest.spyOn(Alert, 'alert').mockImplementation(() => {})})
describe('useApplyPullRequestOTAUpdate', () => { it('detects a running PR deployment from the manifest metadata', () => { mockCurrentlyRunning({ buildChannel: 'testflight', channel: 'pull-request-123', })
const {result} = renderHook(() => useApplyPullRequestOTAUpdate())
expect(result.current.currentChannel).toBe('pull-request-123') expect(result.current.isCurrentlyRunningPullRequestDeployment).toBe(true) expect(result.current.isCurrentlyRunningNonStandardChannel).toBe(true) })
it('treats a standard downloaded update as a standard channel', () => { mockCurrentlyRunning({buildChannel: 'testflight', channel: 'testflight'})
const {result} = renderHook(() => useApplyPullRequestOTAUpdate())
expect(result.current.currentChannel).toBe('testflight') expect(result.current.isCurrentlyRunningPullRequestDeployment).toBe(false) expect(result.current.isCurrentlyRunningNonStandardChannel).toBe(false) })
it('falls back to the build channel for an embedded launch', () => { mockCurrentlyRunning({buildChannel: 'testflight'})
const {result} = renderHook(() => useApplyPullRequestOTAUpdate())
expect(result.current.currentChannel).toBe('testflight') expect(result.current.isCurrentlyRunningNonStandardChannel).toBe(false) })
it('reports no channel when updates are disabled', () => { mockCurrentlyRunning({buildChannel: ''})
const {result} = renderHook(() => useApplyPullRequestOTAUpdate())
expect(result.current.currentChannel).toBeUndefined() expect(result.current.isCurrentlyRunningNonStandardChannel).toBe(false) })
it('stays quiet when already running the latest of the requested channel', async () => { mockCurrentlyRunning({ buildChannel: 'testflight', channel: 'pull-request-123', }) jest.mocked(checkForUpdateAsync).mockResolvedValue({ isAvailable: false, reason: UpdateCheckResultNotAvailableReason.NO_UPDATE_AVAILABLE_ON_SERVER, } as Awaited<ReturnType<typeof checkForUpdateAsync>>) const {result} = renderHook(() => useApplyPullRequestOTAUpdate())
await act(() => result.current.tryApplyUpdate('pull-request-123'))
expect(Alert.alert).not.toHaveBeenCalled() })
it('warns when no deployment is available for a different channel', async () => { mockCurrentlyRunning({ buildChannel: 'testflight', channel: 'pull-request-123', }) jest.mocked(checkForUpdateAsync).mockResolvedValue({ isAvailable: false, reason: UpdateCheckResultNotAvailableReason.NO_UPDATE_AVAILABLE_ON_SERVER, } as Awaited<ReturnType<typeof checkForUpdateAsync>>) const {result} = renderHook(() => useApplyPullRequestOTAUpdate())
await act(() => result.current.tryApplyUpdate('pull-request-456'))
expect(Alert.alert).toHaveBeenCalledWith( 'No Deployment Available', expect.stringContaining('pull-request-456'), ) })
it('stays silent on a re-fired intent even when the app version differs', async () => { mockCurrentlyRunning({ buildChannel: 'testflight', channel: 'pull-request-123', }) jest.mocked(checkForUpdateAsync).mockResolvedValue({ isAvailable: false, reason: UpdateCheckResultNotAvailableReason.NO_UPDATE_AVAILABLE_ON_SERVER, } as Awaited<ReturnType<typeof checkForUpdateAsync>>) const {result} = renderHook(() => useApplyPullRequestOTAUpdate())
await act(() => result.current.tryApplyUpdate('pull-request-123', '0.0.0'))
expect(Alert.alert).not.toHaveBeenCalled() expect(fetchUpdateAsync).not.toHaveBeenCalled() })
it('prompts to apply an available update when the app version matches', async () => { jest.mocked(checkForUpdateAsync).mockResolvedValue({ isAvailable: true, } as Awaited<ReturnType<typeof checkForUpdateAsync>>) const {result} = renderHook(() => useApplyPullRequestOTAUpdate())
await act(() => result.current.tryApplyUpdate('pull-request-123', APP_VERSION), )
expect(Alert.alert).toHaveBeenCalledWith( 'Apply update from PR #123?', expect.stringContaining('relaunch'), expect.arrayContaining([expect.objectContaining({text: 'Apply'})]), ) })
it('warns before applying an OTA built for a different app version', async () => { jest.mocked(checkForUpdateAsync).mockResolvedValue({ isAvailable: true, } as Awaited<ReturnType<typeof checkForUpdateAsync>>) jest.mocked(fetchUpdateAsync).mockResolvedValue({ isNew: true, isRollBackToEmbedded: false, manifest: {id: 'mismatched-update'}, } as Awaited<ReturnType<typeof fetchUpdateAsync>>) const {result} = renderHook(() => useApplyPullRequestOTAUpdate())
await act(() => result.current.tryApplyUpdate('pull-request-123', '0.0.0'))
expect(Alert.alert).toHaveBeenCalledWith( 'App Version Mismatch', expect.stringContaining('Applying it anyway may cause'), expect.arrayContaining([expect.objectContaining({text: 'Apply Anyway'})]), )
const buttons = jest.mocked(Alert.alert).mock.calls[0][2] void act(() => buttons?.[1].onPress?.())
await waitFor(() => expect(reloadAsync).toHaveBeenCalled()) expect(device.set).toHaveBeenCalledWith(['pendingOTAUpdate'], { attemptedAt: expect.any(Number), channel: 'pull-request-123', updateId: 'mismatched-update', }) })
it('informs the user when checking for an OTA fails', async () => { jest.mocked(checkForUpdateAsync).mockRejectedValue(new Error('offline')) const {result} = renderHook(() => useApplyPullRequestOTAUpdate())
await act(() => result.current.tryApplyUpdate('pull-request-123'))
expect(Alert.alert).toHaveBeenCalledWith( 'Update Check Failed', expect.stringContaining('Error: offline'), ) expect(result.current.pending).toBe(false) })
it('informs the user when downloading an OTA fails', async () => { jest.mocked(checkForUpdateAsync).mockResolvedValue({ isAvailable: true, } as Awaited<ReturnType<typeof checkForUpdateAsync>>) jest .mocked(fetchUpdateAsync) .mockRejectedValue(new Error('download failed')) const {result} = renderHook(() => useApplyPullRequestOTAUpdate())
await act(() => result.current.tryApplyUpdate('pull-request-123')) const buttons = jest.mocked(Alert.alert).mock.calls[0][2]
void act(() => buttons?.[1].onPress?.())
await waitFor(() => expect(Alert.alert).toHaveBeenLastCalledWith( 'Update Failed', expect.stringContaining('Error: download failed'), ), ) expect(device.set).not.toHaveBeenCalled() expect(result.current.pending).toBe(false) })
it('clears the recovery marker and informs the user when reloading fails', async () => { jest.mocked(checkForUpdateAsync).mockResolvedValue({ isAvailable: true, } as Awaited<ReturnType<typeof checkForUpdateAsync>>) jest.mocked(fetchUpdateAsync).mockResolvedValue({ isNew: true, isRollBackToEmbedded: false, manifest: {id: 'new-update'}, } as Awaited<ReturnType<typeof fetchUpdateAsync>>) jest.mocked(reloadAsync).mockRejectedValue(new Error('reload failed')) const {result} = renderHook(() => useApplyPullRequestOTAUpdate())
await act(() => result.current.tryApplyUpdate('pull-request-123')) const buttons = jest.mocked(Alert.alert).mock.calls[0][2]
void act(() => buttons?.[1].onPress?.())
await waitFor(() => expect(Alert.alert).toHaveBeenLastCalledWith( 'Update Failed', expect.stringContaining('Error: reload failed'), ), ) expect(device.set).toHaveBeenCalledWith(['pendingOTAUpdate'], { attemptedAt: expect.any(Number), channel: 'pull-request-123', updateId: 'new-update', }) expect(device.remove).toHaveBeenCalledWith(['pendingOTAUpdate']) expect(result.current.pending).toBe(false) })
describe('checkForUpdates', () => { it('offers to relaunch into a newer update of the running channel', async () => { mockCurrentlyRunning({ buildChannel: 'testflight', channel: 'pull-request-123', }) jest.mocked(checkForUpdateAsync).mockResolvedValue({ isAvailable: true, } as Awaited<ReturnType<typeof checkForUpdateAsync>>) jest.mocked(fetchUpdateAsync).mockResolvedValue({ isNew: true, isRollBackToEmbedded: false, manifest: {id: 'new-update'}, } as Awaited<ReturnType<typeof fetchUpdateAsync>>) const {result} = renderHook(() => useApplyPullRequestOTAUpdate())
await act(() => result.current.checkForUpdates())
// The channel rides on the request-header override. An abandoned switch // clears it, so the check names the running channel and no other. expect(setUpdateURLAndRequestHeadersOverride).toHaveBeenCalledTimes(1) expect(setUpdateURLAndRequestHeadersOverride).toHaveBeenCalledWith( expect.objectContaining({ requestHeaders: {'expo-channel-name': 'pull-request-123'}, }), ) expect(setExtraParamAsync).not.toHaveBeenCalledWith( 'channel', expect.anything(), ) expect(Alert.alert).toHaveBeenCalledWith( 'Update Available', expect.stringContaining('PR #123'), expect.arrayContaining([expect.objectContaining({text: 'Relaunch'})]), )
const buttons = jest.mocked(Alert.alert).mock.calls[0][2] void act(() => buttons?.[1].onPress?.())
await waitFor(() => expect(reloadAsync).toHaveBeenCalled()) expect(result.current.pending).toBe(false) })
it('reports being up to date on a standard channel', async () => { mockCurrentlyRunning({buildChannel: 'testflight', channel: 'testflight'}) jest.mocked(checkForUpdateAsync).mockResolvedValue({ isAvailable: false, reason: UpdateCheckResultNotAvailableReason.NO_UPDATE_AVAILABLE_ON_SERVER, } as Awaited<ReturnType<typeof checkForUpdateAsync>>) const {result} = renderHook(() => useApplyPullRequestOTAUpdate())
await act(() => result.current.checkForUpdates())
expect(setUpdateURLAndRequestHeadersOverride).not.toHaveBeenCalled() expect(Alert.alert).toHaveBeenCalledWith( 'Up to Date', expect.stringContaining('testflight'), ) expect(fetchUpdateAsync).not.toHaveBeenCalled() })
it('informs the user when the check fails', async () => { jest.mocked(checkForUpdateAsync).mockRejectedValue(new Error('offline')) const {result} = renderHook(() => useApplyPullRequestOTAUpdate())
await act(() => result.current.checkForUpdates())
expect(Alert.alert).toHaveBeenCalledWith( 'Update Check Failed', expect.stringContaining('Error: offline'), ) expect(result.current.pending).toBe(false) }) })})
describe('useOTAUpdateRecovery', () => { it('informs the user when Expo fell back from the attempted OTA', async () => { jest.mocked(device.get).mockReturnValue({ attemptedAt: Date.now(), channel: 'pull-request-123', updateId: 'failed-update', })
renderHook(() => useOTAUpdateRecovery())
await waitFor(() => expect(Alert.alert).toHaveBeenCalledWith( 'Update Failed', expect.stringContaining('PR #123 deployment could not start'), ), ) expect(device.remove).toHaveBeenCalledWith(['pendingOTAUpdate']) expect(logger.error).toHaveBeenCalledWith( 'Custom OTA Update Failed to Launch', expect.objectContaining({attemptedUpdateId: 'failed-update'}), ) })
it('recognizes a launched OTA when the update ID casing differs', () => { jest.mocked(device.get).mockReturnValue({ attemptedAt: Date.now(), channel: 'pull-request-123', updateId: currentUpdate.updateId.toUpperCase(), })
renderHook(() => useOTAUpdateRecovery())
expect(device.remove).toHaveBeenCalledWith(['pendingOTAUpdate']) expect(Alert.alert).not.toHaveBeenCalled() expect(logger.error).not.toHaveBeenCalled() })
it('silently clears a stale marker from an older OTA bundle', () => { jest.mocked(device.get).mockReturnValue({ attemptedAt: Date.now() - 10 * 60e3, channel: 'pull-request-123', updateId: 'older-update', })
renderHook(() => useOTAUpdateRecovery())
expect(device.remove).toHaveBeenCalledWith(['pendingOTAUpdate']) expect(Alert.alert).not.toHaveBeenCalled() expect(logger.error).not.toHaveBeenCalled() })})