Skip to content

Commit

Permalink
fix: add retry tests
Browse files Browse the repository at this point in the history
  • Loading branch information
janek26 committed Oct 26, 2023
1 parent e00ba27 commit 8d69f87
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/shared/chrome.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
44 changes: 44 additions & 0 deletions test/retry.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});

0 comments on commit 8d69f87

Please sign in to comment.