From 48841776d189d9d5eb09e262d5080dcb49cb6401 Mon Sep 17 00:00:00 2001 From: staszekscp Date: Mon, 9 Nov 2026 09:56:20 +0100 Subject: [PATCH 1/4] Fix react-native-pdf throws undefined is not a function when a PDF download is canceled --- patches/react-native-pdf/details.md | 17 ++ ...f+7.0.2+007+fix-cancel-download-task.patch | 99 ++++++++++ tests/unit/ReactNativePDFDownloadTest.tsx | 174 ++++++++++++++++++ 3 files changed, 290 insertions(+) create mode 100644 patches/react-native-pdf/react-native-pdf+7.0.2+007+fix-cancel-download-task.patch create mode 100644 tests/unit/ReactNativePDFDownloadTest.tsx diff --git a/patches/react-native-pdf/details.md b/patches/react-native-pdf/details.md index 8f00de232f70..1e49d8ac0433 100644 --- a/patches/react-native-pdf/details.md +++ b/patches/react-native-pdf/details.md @@ -94,3 +94,20 @@ - Upstream PR/issue: https://github.com/wonday/react-native-pdf/pull/1050, https://github.com/wonday/react-native-pdf/issues/1049 - E/App issue: https://github.com/Expensify/App/issues/103207 - PR introducing patch: https://github.com/Expensify/App/pull/103781 + + +### [react-native-pdf+7.0.2+007+fix-cancel-download-task.patch](react-native-pdf+7.0.2+007+fix-cancel-download-task.patch) + +- Reason: + + ``` + This patch fixes an unhandled "TypeError: undefined is not a function" from `this.lastRNBFTask.cancel()` when the PDF source changes while a download is still running, e.g. when the encrypted auth token in a receipt URL is refreshed after reauthentication. + + `_downloadFile` stored the promise returned by `.catch()` in `lastRNBFTask` instead of the react-native-blob-util task, so it had no `cancel()`. `componentDidUpdate` then loaded the new source without canceling, and the next `_downloadFile` called `lastRNBFTask.cancel()` and threw. `_prepareFile` doesn't await `_downloadFile`, so the error became an unhandled promise rejection. + + The patch stores the task itself and checks `cancel()` before calling it. Each download gets an id, and a canceled or replaced download ignores its result, so a cancellation isn't reported to `onError` and an old download can't replace the current PDF. `componentDidUpdate` loads the new source right away instead of in the cancel callback, which react-native-blob-util doesn't call when the request has already finished. A failed download is now reported to `onError` once, instead of also being copied to the cache and shown. + ``` + +- Upstream PR/issue: https://github.com/wonday/react-native-pdf/pull/1057. Since 7.0.5, react-native-pdf stores the cancelable task (https://github.com/wonday/react-native-pdf/pull/1031) but still reports a canceled download to `onError`. This patch can be dropped once #1057 is released. +- E/App issue: https://github.com/Expensify/App/issues/106338 +- PR introducing patch: TBD diff --git a/patches/react-native-pdf/react-native-pdf+7.0.2+007+fix-cancel-download-task.patch b/patches/react-native-pdf/react-native-pdf+7.0.2+007+fix-cancel-download-task.patch new file mode 100644 index 000000000000..924baa9e146f --- /dev/null +++ b/patches/react-native-pdf/react-native-pdf+7.0.2+007+fix-cancel-download-task.patch @@ -0,0 +1,99 @@ +diff --git a/node_modules/react-native-pdf/index.js b/node_modules/react-native-pdf/index.js +--- a/node_modules/react-native-pdf/index.js ++++ b/node_modules/react-native-pdf/index.js +@@ -119,6 +119,8 @@ export default class Pdf extends Component { + }; + + this.lastRNBFTask = null; ++ // Goes up whenever a download starts or is canceled, so a download can tell it was replaced ++ this._downloadId = 0; + + } + +@@ -128,15 +130,11 @@ export default class Pdf extends Component { + const curSource = Image.resolveAssetSource(prevProps.source); + + if ((nextSource.uri !== curSource.uri)) { +- // if has download task, then cancel it. +- if (this.lastRNBFTask && this.lastRNBFTask.cancel) { +- this.lastRNBFTask.cancel(err => { +- this._loadFromSource(this.props.source); +- }); +- this.lastRNBFTask = null; +- } else { +- this._loadFromSource(this.props.source); +- } ++ // Cancel the download of the previous source and load the new one right away. The canceled download ++ // ignores its result, so there's no need to wait for the cancel callback, which react-native-blob-util ++ // doesn't call when the request has already finished. ++ this._cancelDownload(); ++ this._loadFromSource(this.props.source); + } + } + +@@ -250,17 +248,30 @@ export default class Pdf extends Component { + + }; + +- _downloadFile = async (source, cacheFile) => { +- +- if (this.lastRNBFTask) { +- this.lastRNBFTask.cancel(err => { ++ _cancelDownload = () => { ++ // A download that is still running belongs to a source that is no longer wanted ++ this._downloadId += 1; ++ const task = this.lastRNBFTask; ++ this.lastRNBFTask = null; ++ if (task && typeof task.cancel === 'function') { ++ task.cancel(err => { + }); +- this.lastRNBFTask = null; + } ++ }; ++ ++ _downloadFile = async (source, cacheFile) => { ++ ++ // Only one download runs at a time ++ this._cancelDownload(); ++ const downloadId = this._downloadId; ++ // False once this download was canceled or a newer one started. Its result is then ignored: canceling ++ // rejects the task, which isn't an error to report, and a replaced download must not show its file. ++ const isCurrentDownload = () => this._downloadId === downloadId; + + const tempCacheFile = cacheFile + '.tmp'; + this._unlinkFile(tempCacheFile); + ++ // Store the task itself, which has cancel(). The promise that catch() returned, stored here before, doesn't. + this.lastRNBFTask = ReactNativeBlobUtil.config({ + // response data will be saved to this path if it has access right. + path: tempCacheFile, +@@ -278,9 +289,6 @@ export default class Pdf extends Component { + if (this._mounted) { + this.setState({progress: received / total}); + } +- }) +- .catch(async (error) => { +- this._onError(error); + }); + + this.lastRNBFTask +@@ -313,6 +321,9 @@ export default class Pdf extends Component { + ReactNativeBlobUtil.fs + .cp(tempCacheFile, cacheFile) + .then(() => { ++ if (!isCurrentDownload()) { ++ return; ++ } + if (this._mounted) { + this.setState({path: cacheFile, isDownloaded: true, progress: 1}); + } +@@ -323,6 +334,9 @@ export default class Pdf extends Component { + }); + }) + .catch(async (error) => { ++ if (!isCurrentDownload()) { ++ return; ++ } + this._unlinkFile(tempCacheFile); + this._unlinkFile(cacheFile); + this._onError(error); diff --git a/tests/unit/ReactNativePDFDownloadTest.tsx b/tests/unit/ReactNativePDFDownloadTest.tsx new file mode 100644 index 000000000000..e80c4eff4d7d --- /dev/null +++ b/tests/unit/ReactNativePDFDownloadTest.tsx @@ -0,0 +1,174 @@ +/** + * Runs the real react-native-pdf JS (node_modules/react-native-pdf/index.js, with our patches) with react-native-blob-util + * mocked. NativePDFViewTest mocks react-native-pdf out, so it can't catch problems in the library's own download code. + * + * Regression tests for https://github.com/Expensify/App/issues/106338: changing the PDF source while a download was + * running threw "undefined is not a function" from `lastRNBFTask.cancel()` as an unhandled promise rejection. + */ +import {render, screen} from '@testing-library/react-native'; + +import {createHash} from 'crypto'; +import React from 'react'; +import Pdf from 'react-native-pdf'; + +import waitForBatchedUpdatesWithAct from '../utils/waitForBatchedUpdatesWithAct'; + +type MockTask = Promise<{respInfo: {headers: Record}}> & { + uri: string; + isCanceled: boolean; + cancel: jest.Mock; + progress: () => MockTask; + finish: () => void; + fail: (error: Error) => void; +}; + +const mockTasks: MockTask[] = []; +const mockCachedFiles = new Set(); + +jest.mock('react-native-blob-util', () => { + const createTask = (uri: string): MockTask => { + let resolveTask: (response: {respInfo: {headers: Record}}) => void = () => {}; + let rejectTask: (reason: unknown) => void = () => {}; + const task = new Promise((resolve, reject) => { + resolveTask = resolve; + rejectTask = reject; + }) as MockTask; + + // Like react-native-blob-util: cancel() rejects the task, and once the task has settled it's a no-op that + // never calls its callback + const settle = () => { + task.cancel = jest.fn(); + }; + task.uri = uri; + task.isCanceled = false; + task.progress = () => task; + task.cancel = jest.fn((callback?: (error: unknown) => void) => { + task.isCanceled = true; + settle(); + rejectTask(new Error('canceled')); + callback?.(null); + }); + task.finish = () => { + settle(); + resolveTask({respInfo: {headers: {}}}); + }; + task.fail = (error: Error) => { + settle(); + rejectTask(error); + }; + mockTasks.push(task); + return task; + }; + + return { + __esModule: true, + default: { + config: () => ({fetch: (_method: string, uri: string) => createTask(uri)}), + fs: { + dirs: {CacheDir: '/cache'}, + stat: jest.fn((path: string) => (mockCachedFiles.has(path) ? Promise.resolve({lastModified: Date.now()}) : Promise.reject(new Error('not cached')))), + unlink: jest.fn(() => Promise.resolve()), + cp: jest.fn(() => Promise.resolve()), + }, + }, + }; +}); + +jest.mock('react-native-pdf/fabric/RNPDFPdfNativeComponent', () => ({__esModule: true, default: 'RNPDFPdfView', Commands: {}})); +jest.mock('react-native-pdf/PdfView', () => () => null); + +type PdfInternals = { + state: {path: string; isDownloaded: boolean}; + _downloadFile: (...args: unknown[]) => Promise; +}; + +const URL_WITH_OLD_TOKEN = 'https://www.expensify.com/receipts/w_1.pdf?encryptedAuthToken=old'; +const URL_WITH_NEW_TOKEN = 'https://www.expensify.com/receipts/w_1.pdf?encryptedAuthToken=new'; + +// react-native-pdf names the cache file after the SHA-1 of the URI +const getCacheFile = (uri: string) => `/cache/${createHash('sha1').update(uri).digest('hex')}.pdf`; + +function renderPdf(uri: string, onError: jest.Mock) { + const renderWithSource = (sourceURI: string) => ( + + ); + const {rerender} = render(renderWithSource(uri)); + const pdf = screen.UNSAFE_getByType(Pdf).instance as PdfInternals; + + // The library doesn't await _downloadFile, so in the app a rejection from it is an unhandled promise rejection + const escapedRejections: unknown[] = []; + const downloadFile = pdf._downloadFile; + pdf._downloadFile = (...args) => { + const download = downloadFile(...args); + download.catch((error: unknown) => escapedRejections.push(error)); + return download; + }; + + return {pdf, escapedRejections, changeSource: (nextURI: string) => rerender(renderWithSource(nextURI))}; +} + +describe('react-native-pdf download cancellation', () => { + beforeEach(() => { + mockTasks.length = 0; + mockCachedFiles.clear(); + }); + + it('cancels the old download and shows the new source when the source changes during a download', async () => { + // Given a PDF whose download is still running + const onError = jest.fn(); + const {pdf, escapedRejections, changeSource} = renderPdf(URL_WITH_OLD_TOKEN, onError); + await waitForBatchedUpdatesWithAct(); + + // When the auth token in its URL is refreshed and the new download finishes + changeSource(URL_WITH_NEW_TOKEN); + await waitForBatchedUpdatesWithAct(); + mockTasks.at(1)?.finish(); + await waitForBatchedUpdatesWithAct(); + + // Then the old download is canceled without an error and the new one is shown + expect(mockTasks.map((task) => task.uri)).toEqual([URL_WITH_OLD_TOKEN, URL_WITH_NEW_TOKEN]); + expect(mockTasks.at(0)?.isCanceled).toBe(true); + expect(escapedRejections).toEqual([]); + expect(onError).not.toHaveBeenCalled(); + expect(pdf.state).toMatchObject({path: getCacheFile(URL_WITH_NEW_TOKEN), isDownloaded: true}); + }); + + it('ignores a download that finished just before the source changed', async () => { + // Given a PDF whose download finishes right when its source changes to one that's already cached + const onError = jest.fn(); + const {pdf, escapedRejections, changeSource} = renderPdf(URL_WITH_OLD_TOKEN, onError); + await waitForBatchedUpdatesWithAct(); + mockCachedFiles.add(getCacheFile(URL_WITH_NEW_TOKEN)); + + // When the finished download is handled after the source changed + mockTasks.at(0)?.finish(); + changeSource(URL_WITH_NEW_TOKEN); + await waitForBatchedUpdatesWithAct(); + + // Then the new source stays shown + expect(escapedRejections).toEqual([]); + expect(onError).not.toHaveBeenCalled(); + expect(pdf.state).toMatchObject({path: getCacheFile(URL_WITH_NEW_TOKEN), isDownloaded: true}); + }); + + it('reports a failed download once', async () => { + // Given a PDF whose download is running + const onError = jest.fn(); + const {pdf, escapedRejections} = renderPdf(URL_WITH_NEW_TOKEN, onError); + await waitForBatchedUpdatesWithAct(); + + // When the download fails + const networkError = new Error('network failure'); + mockTasks.at(0)?.fail(networkError); + await waitForBatchedUpdatesWithAct(); + + // Then the error is reported once and nothing is shown as downloaded + expect(onError).toHaveBeenCalledTimes(1); + expect(onError).toHaveBeenCalledWith(networkError); + expect(pdf.state.isDownloaded).toBe(false); + expect(escapedRejections).toEqual([]); + }); +}); From 3d0eb1b267335eb1620924c6ac3e949b29a1420c Mon Sep 17 00:00:00 2001 From: staszekscp Date: Mon, 9 Nov 2026 13:55:46 +0100 Subject: [PATCH 2/4] Fixes --- tests/unit/ReactNativePDFDownloadTest.tsx | 68 ++++++++++++++--------- 1 file changed, 41 insertions(+), 27 deletions(-) diff --git a/tests/unit/ReactNativePDFDownloadTest.tsx b/tests/unit/ReactNativePDFDownloadTest.tsx index e80c4eff4d7d..f849c4e532fd 100644 --- a/tests/unit/ReactNativePDFDownloadTest.tsx +++ b/tests/unit/ReactNativePDFDownloadTest.tsx @@ -1,3 +1,4 @@ +// cspell:ignore RNBF RNPDF /** * Runs the real react-native-pdf JS (node_modules/react-native-pdf/index.js, with our patches) with react-native-blob-util * mocked. NativePDFViewTest mocks react-native-pdf out, so it can't catch problems in the library's own download code. @@ -13,7 +14,9 @@ import Pdf from 'react-native-pdf'; import waitForBatchedUpdatesWithAct from '../utils/waitForBatchedUpdatesWithAct'; -type MockTask = Promise<{respInfo: {headers: Record}}> & { +type MockResponse = {respInfo: {headers: Record}}; + +type MockTask = Promise & { uri: string; isCanceled: boolean; cancel: jest.Mock; @@ -27,35 +30,38 @@ const mockCachedFiles = new Set(); jest.mock('react-native-blob-util', () => { const createTask = (uri: string): MockTask => { - let resolveTask: (response: {respInfo: {headers: Record}}) => void = () => {}; + let resolveTask: (response: MockResponse) => void = () => {}; let rejectTask: (reason: unknown) => void = () => {}; - const task = new Promise((resolve, reject) => { + let isSettled = false; + const promise = new Promise((resolve, reject) => { resolveTask = resolve; rejectTask = reject; - }) as MockTask; - - // Like react-native-blob-util: cancel() rejects the task, and once the task has settled it's a no-op that - // never calls its callback - const settle = () => { - task.cancel = jest.fn(); - }; - task.uri = uri; - task.isCanceled = false; - task.progress = () => task; - task.cancel = jest.fn((callback?: (error: unknown) => void) => { - task.isCanceled = true; - settle(); - rejectTask(new Error('canceled')); - callback?.(null); }); - task.finish = () => { - settle(); - resolveTask({respInfo: {headers: {}}}); - }; - task.fail = (error: Error) => { - settle(); - rejectTask(error); - }; + + const task: MockTask = Object.assign(promise, { + uri, + isCanceled: false, + progress: () => task, + // Like react-native-blob-util: cancel() rejects the task, and once the task has settled it's a no-op that + // never calls its callback + cancel: jest.fn((callback?: (error: unknown) => void) => { + if (isSettled) { + return; + } + isSettled = true; + task.isCanceled = true; + rejectTask(new Error('canceled')); + callback?.(null); + }), + finish: () => { + isSettled = true; + resolveTask({respInfo: {headers: {}}}); + }, + fail: (error: Error) => { + isSettled = true; + rejectTask(error); + }, + }); mockTasks.push(task); return task; }; @@ -79,9 +85,14 @@ jest.mock('react-native-pdf/PdfView', () => () => null); type PdfInternals = { state: {path: string; isDownloaded: boolean}; + // eslint-disable-next-line @typescript-eslint/naming-convention -- react-native-pdf's own method name _downloadFile: (...args: unknown[]) => Promise; }; +function isPdfInternals(instance: unknown): instance is PdfInternals { + return typeof instance === 'object' && instance !== null && 'state' in instance && '_downloadFile' in instance; +} + const URL_WITH_OLD_TOKEN = 'https://www.expensify.com/receipts/w_1.pdf?encryptedAuthToken=old'; const URL_WITH_NEW_TOKEN = 'https://www.expensify.com/receipts/w_1.pdf?encryptedAuthToken=new'; @@ -96,7 +107,10 @@ function renderPdf(uri: string, onError: jest.Mock) { /> ); const {rerender} = render(renderWithSource(uri)); - const pdf = screen.UNSAFE_getByType(Pdf).instance as PdfInternals; + const pdf: unknown = screen.UNSAFE_getByType(Pdf).instance; + if (!isPdfInternals(pdf)) { + throw new Error('Expected the react-native-pdf component instance'); + } // The library doesn't await _downloadFile, so in the app a rejection from it is an unhandled promise rejection const escapedRejections: unknown[] = []; From 516128feda1901546d20f87baef6b5a67aac9b63 Mon Sep 17 00:00:00 2001 From: staszekscp Date: Mon, 9 Nov 2026 14:22:25 +0100 Subject: [PATCH 3/4] Fixes --- tests/unit/ReactNativePDFDownloadTest.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/unit/ReactNativePDFDownloadTest.tsx b/tests/unit/ReactNativePDFDownloadTest.tsx index f849c4e532fd..eb0898dc9466 100644 --- a/tests/unit/ReactNativePDFDownloadTest.tsx +++ b/tests/unit/ReactNativePDFDownloadTest.tsx @@ -114,12 +114,12 @@ function renderPdf(uri: string, onError: jest.Mock) { // The library doesn't await _downloadFile, so in the app a rejection from it is an unhandled promise rejection const escapedRejections: unknown[] = []; - const downloadFile = pdf._downloadFile; - pdf._downloadFile = (...args) => { + const {_downloadFile: downloadFile} = pdf; + jest.spyOn(pdf, '_downloadFile').mockImplementation((...args) => { const download = downloadFile(...args); download.catch((error: unknown) => escapedRejections.push(error)); return download; - }; + }); return {pdf, escapedRejections, changeSource: (nextURI: string) => rerender(renderWithSource(nextURI))}; } From d45350d892251a361013fa2304cdd2be4dc2aba7 Mon Sep 17 00:00:00 2001 From: staszekscp Date: Tue, 10 Nov 2026 09:28:45 +0100 Subject: [PATCH 4/4] Address review --- patches/react-native-pdf/details.md | 4 +-- ...f+7.0.2+007+fix-cancel-download-task.patch | 35 ++++++++++++++++--- tests/unit/ReactNativePDFDownloadTest.tsx | 27 +++++++++++++- 3 files changed, 59 insertions(+), 7 deletions(-) diff --git a/patches/react-native-pdf/details.md b/patches/react-native-pdf/details.md index 1e49d8ac0433..4e21fdc41878 100644 --- a/patches/react-native-pdf/details.md +++ b/patches/react-native-pdf/details.md @@ -105,9 +105,9 @@ `_downloadFile` stored the promise returned by `.catch()` in `lastRNBFTask` instead of the react-native-blob-util task, so it had no `cancel()`. `componentDidUpdate` then loaded the new source without canceling, and the next `_downloadFile` called `lastRNBFTask.cancel()` and threw. `_prepareFile` doesn't await `_downloadFile`, so the error became an unhandled promise rejection. - The patch stores the task itself and checks `cancel()` before calling it. Each download gets an id, and a canceled or replaced download ignores its result, so a cancellation isn't reported to `onError` and an old download can't replace the current PDF. `componentDidUpdate` loads the new source right away instead of in the cancel callback, which react-native-blob-util doesn't call when the request has already finished. A failed download is now reported to `onError` once, instead of also being copied to the cache and shown. + The patch stores the task itself and checks `cancel()` before calling it. Each download gets an id, and a canceled or replaced download ignores its result, so a cancellation isn't reported to `onError` and an old download can't replace the current PDF. `componentDidUpdate` loads the new source right away instead of in the cancel callback, which react-native-blob-util doesn't call when the request has already finished. A failed download is now reported to `onError` once, instead of also being copied to the cache and shown. A cache check that ends after the source changed is ignored too, so it can't start a download of the old source that cancels the new one. ``` - Upstream PR/issue: https://github.com/wonday/react-native-pdf/pull/1057. Since 7.0.5, react-native-pdf stores the cancelable task (https://github.com/wonday/react-native-pdf/pull/1031) but still reports a canceled download to `onError`. This patch can be dropped once #1057 is released. - E/App issue: https://github.com/Expensify/App/issues/106338 -- PR introducing patch: TBD +- PR introducing patch: https://github.com/Expensify/App/pull/106351 diff --git a/patches/react-native-pdf/react-native-pdf+7.0.2+007+fix-cancel-download-task.patch b/patches/react-native-pdf/react-native-pdf+7.0.2+007+fix-cancel-download-task.patch index 924baa9e146f..e174229a7266 100644 --- a/patches/react-native-pdf/react-native-pdf+7.0.2+007+fix-cancel-download-task.patch +++ b/patches/react-native-pdf/react-native-pdf+7.0.2+007+fix-cancel-download-task.patch @@ -31,7 +31,34 @@ diff --git a/node_modules/react-native-pdf/index.js b/node_modules/react-native- } } -@@ -250,17 +248,30 @@ export default class Pdf extends Component { +@@ -167,10 +165,16 @@ export default class Pdf extends Component { + const filename = source.cacheFileName || SHA1(uri) + '.pdf'; + const cacheFile = ReactNativeBlobUtil.fs.dirs.CacheDir + '/' + filename; + ++ // The cache check is async, so the source can change before it ends. Only the latest source may load. ++ const isCurrentSource = () => (Image.resolveAssetSource(this.props.source) || {}).uri === source.uri; ++ + if (source.cache) { + ReactNativeBlobUtil.fs + .stat(cacheFile) + .then(stats => { ++ if (!isCurrentSource()) { ++ return; ++ } + if (!Boolean(source.expiration) || (source.expiration * 1000 + stats.lastModified) > (new Date().getTime())) { + if (this._mounted) { + this.setState({path: cacheFile, isDownloaded: true}); +@@ -181,6 +185,9 @@ export default class Pdf extends Component { + } + }) + .catch(() => { ++ if (!isCurrentSource()) { ++ return; ++ } + this._prepareFile(source); + }) + +@@ -250,17 +257,30 @@ export default class Pdf extends Component { }; @@ -67,7 +94,7 @@ diff --git a/node_modules/react-native-pdf/index.js b/node_modules/react-native- this.lastRNBFTask = ReactNativeBlobUtil.config({ // response data will be saved to this path if it has access right. path: tempCacheFile, -@@ -278,9 +289,6 @@ export default class Pdf extends Component { +@@ -278,9 +298,6 @@ export default class Pdf extends Component { if (this._mounted) { this.setState({progress: received / total}); } @@ -77,7 +104,7 @@ diff --git a/node_modules/react-native-pdf/index.js b/node_modules/react-native- }); this.lastRNBFTask -@@ -313,6 +321,9 @@ export default class Pdf extends Component { +@@ -313,6 +330,9 @@ export default class Pdf extends Component { ReactNativeBlobUtil.fs .cp(tempCacheFile, cacheFile) .then(() => { @@ -87,7 +114,7 @@ diff --git a/node_modules/react-native-pdf/index.js b/node_modules/react-native- if (this._mounted) { this.setState({path: cacheFile, isDownloaded: true, progress: 1}); } -@@ -323,6 +334,9 @@ export default class Pdf extends Component { +@@ -323,6 +343,9 @@ export default class Pdf extends Component { }); }) .catch(async (error) => { diff --git a/tests/unit/ReactNativePDFDownloadTest.tsx b/tests/unit/ReactNativePDFDownloadTest.tsx index eb0898dc9466..aac695c3ecda 100644 --- a/tests/unit/ReactNativePDFDownloadTest.tsx +++ b/tests/unit/ReactNativePDFDownloadTest.tsx @@ -27,6 +27,8 @@ type MockTask = Promise & { const mockTasks: MockTask[] = []; const mockCachedFiles = new Set(); +// Cache checks wait for this before they settle, so a test can change the source while one is running +let mockCacheCheckGate: Promise = Promise.resolve(); jest.mock('react-native-blob-util', () => { const createTask = (uri: string): MockTask => { @@ -72,7 +74,7 @@ jest.mock('react-native-blob-util', () => { config: () => ({fetch: (_method: string, uri: string) => createTask(uri)}), fs: { dirs: {CacheDir: '/cache'}, - stat: jest.fn((path: string) => (mockCachedFiles.has(path) ? Promise.resolve({lastModified: Date.now()}) : Promise.reject(new Error('not cached')))), + stat: jest.fn((path: string) => mockCacheCheckGate.then(() => (mockCachedFiles.has(path) ? {lastModified: Date.now()} : Promise.reject(new Error('not cached'))))), unlink: jest.fn(() => Promise.resolve()), cp: jest.fn(() => Promise.resolve()), }, @@ -128,6 +130,7 @@ describe('react-native-pdf download cancellation', () => { beforeEach(() => { mockTasks.length = 0; mockCachedFiles.clear(); + mockCacheCheckGate = Promise.resolve(); }); it('cancels the old download and shows the new source when the source changes during a download', async () => { @@ -168,6 +171,28 @@ describe('react-native-pdf download cancellation', () => { expect(pdf.state).toMatchObject({path: getCacheFile(URL_WITH_NEW_TOKEN), isDownloaded: true}); }); + it('ignores a cache check that finishes after the source changed', async () => { + // Given a PDF whose cache check is still running + let finishCacheChecks: () => void = () => {}; + mockCacheCheckGate = new Promise((resolve) => { + finishCacheChecks = resolve; + }); + const onError = jest.fn(); + const {pdf, escapedRejections, changeSource} = renderPdf(URL_WITH_OLD_TOKEN, onError); + + // When the source changes to a cached file before that check ends + mockCachedFiles.add(getCacheFile(URL_WITH_NEW_TOKEN)); + changeSource(URL_WITH_NEW_TOKEN); + finishCacheChecks(); + await waitForBatchedUpdatesWithAct(); + + // Then the old source isn't downloaded and the new one is shown + expect(mockTasks).toHaveLength(0); + expect(escapedRejections).toEqual([]); + expect(onError).not.toHaveBeenCalled(); + expect(pdf.state).toMatchObject({path: getCacheFile(URL_WITH_NEW_TOKEN), isDownloaded: true}); + }); + it('reports a failed download once', async () => { // Given a PDF whose download is running const onError = jest.fn();