Skip to content

Commit 8d69f87

Browse files
committed
fix: add retry tests
1 parent e00ba27 commit 8d69f87

File tree

2 files changed

+46
-2
lines changed

2 files changed

+46
-2
lines changed

src/shared/chrome.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,8 @@ export async function autoConnect(
1414
) {
1515
const port = await retry(
1616
() => browser.runtime.connect(),
17-
3, // 3 retries
18-
(retry) => wait(retry * 150), // 150ms, 300ms, max total wait 450ms
17+
3, // 3 retries plus the initial try, so 4 total tries
18+
(retry) => wait(retry * 100), // 100ms, 200ms, 300ms, max total wait 600ms
1919
);
2020
console.log('Port connected');
2121
const cleanUp = onConnect(port);

test/retry.test.ts

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import { retry, wait } from '../src/shared/retry';
2+
3+
describe('retry function', () => {
4+
it('should retry the function for the specified number of times', async () => {
5+
let counter = 0;
6+
const fn = () => {
7+
counter++;
8+
if (counter < 3) {
9+
throw new Error('Error');
10+
}
11+
return 'Success';
12+
};
13+
const result = await retry(fn, 3, wait);
14+
expect(result).toBe('Success');
15+
});
16+
17+
it('should throw an error if the function fails after the specified number of retries', async () => {
18+
const fn = () => {
19+
throw new Error('Error');
20+
};
21+
await expect(retry(fn, 3, wait)).rejects.toThrow('Error');
22+
});
23+
24+
it('should pass the number of retries to the wait function', async () => {
25+
const fn = () => {
26+
throw new Error('Error');
27+
};
28+
const waitFn = jest.fn(wait);
29+
await expect(retry(fn, 3, waitFn)).rejects.toThrow('Error');
30+
expect(waitFn).toHaveBeenCalledTimes(3);
31+
expect(waitFn).toHaveBeenNthCalledWith(1, 1);
32+
expect(waitFn).toHaveBeenNthCalledWith(2, 2);
33+
expect(waitFn).toHaveBeenNthCalledWith(3, 3);
34+
});
35+
});
36+
37+
describe('wait function', () => {
38+
it('should wait for the specified number of milliseconds', async () => {
39+
const start = Date.now();
40+
await wait(100);
41+
const end = Date.now();
42+
expect(end - start).toBeGreaterThanOrEqual(100);
43+
});
44+
});

0 commit comments

Comments
 (0)