From 8d69f87bb7cb2148e2b3c46bfb4d95eea17df4a3 Mon Sep 17 00:00:00 2001 From: Janek Date: Thu, 26 Oct 2023 13:31:04 +0200 Subject: [PATCH] fix: add retry tests --- src/shared/chrome.ts | 4 ++-- test/retry.test.ts | 44 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 2 deletions(-) create mode 100644 test/retry.test.ts diff --git a/src/shared/chrome.ts b/src/shared/chrome.ts index 09291d8..581b919 100644 --- a/src/shared/chrome.ts +++ b/src/shared/chrome.ts @@ -14,8 +14,8 @@ export async function autoConnect( ) { const port = await retry( () => browser.runtime.connect(), - 3, // 3 retries - (retry) => wait(retry * 150), // 150ms, 300ms, max total wait 450ms + 3, // 3 retries plus the initial try, so 4 total tries + (retry) => wait(retry * 100), // 100ms, 200ms, 300ms, max total wait 600ms ); console.log('Port connected'); const cleanUp = onConnect(port); diff --git a/test/retry.test.ts b/test/retry.test.ts new file mode 100644 index 0000000..ba354c5 --- /dev/null +++ b/test/retry.test.ts @@ -0,0 +1,44 @@ +import { retry, wait } from '../src/shared/retry'; + +describe('retry function', () => { + it('should retry the function for the specified number of times', async () => { + let counter = 0; + const fn = () => { + counter++; + if (counter < 3) { + throw new Error('Error'); + } + return 'Success'; + }; + const result = await retry(fn, 3, wait); + expect(result).toBe('Success'); + }); + + it('should throw an error if the function fails after the specified number of retries', async () => { + const fn = () => { + throw new Error('Error'); + }; + await expect(retry(fn, 3, wait)).rejects.toThrow('Error'); + }); + + it('should pass the number of retries to the wait function', async () => { + const fn = () => { + throw new Error('Error'); + }; + const waitFn = jest.fn(wait); + await expect(retry(fn, 3, waitFn)).rejects.toThrow('Error'); + expect(waitFn).toHaveBeenCalledTimes(3); + expect(waitFn).toHaveBeenNthCalledWith(1, 1); + expect(waitFn).toHaveBeenNthCalledWith(2, 2); + expect(waitFn).toHaveBeenNthCalledWith(3, 3); + }); +}); + +describe('wait function', () => { + it('should wait for the specified number of milliseconds', async () => { + const start = Date.now(); + await wait(100); + const end = Date.now(); + expect(end - start).toBeGreaterThanOrEqual(100); + }); +});