Skip to content

Commit 8ae6ee4

Browse files
committed
Add tests to rate-limiting function
1 parent 12872aa commit 8ae6ee4

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

test/rate-limiting.test.ts

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
import { GOOGLE_IMG_SCRAP } from '../dist';
2+
import axios from 'axios';
3+
4+
describe('Rate Limiting test', function () {
5+
// Mock axios to simulate rate limit responses
6+
const mockAxios = jest.spyOn(axios, 'get');
7+
8+
afterEach(() => {
9+
jest.clearAllMocks();
10+
});
11+
12+
it('Should retry on 429 error and eventually succeed', async function () {
13+
// Mock sequence: 429 -> 429 -> success
14+
mockAxios
15+
.mockRejectedValueOnce({ response: { status: 429 } })
16+
.mockRejectedValueOnce({ response: { status: 429 } })
17+
.mockResolvedValueOnce({ data: '<html>...</html>' });
18+
19+
const { result } = await GOOGLE_IMG_SCRAP({
20+
search: 'cats',
21+
limit: 5
22+
});
23+
24+
expect(mockAxios).toHaveBeenCalledTimes(3);
25+
expect(result.length).toBeGreaterThan(0);
26+
});
27+
28+
it('Should throw error after max retries', async function () {
29+
// Mock sequence: 429 -> 429 -> 429 -> 429 (exceeds max retries)
30+
mockAxios
31+
.mockRejectedValue({ response: { status: 429 } });
32+
33+
await expect(GOOGLE_IMG_SCRAP({
34+
search: 'cats',
35+
limit: 5
36+
})).rejects.toThrow('Too many requests. Please try again later.');
37+
});
38+
39+
it('Should handle non-429 errors immediately', async function () {
40+
// Mock 500 error (should not retry)
41+
mockAxios.mockRejectedValue({ response: { status: 500 } });
42+
43+
await expect(GOOGLE_IMG_SCRAP({
44+
search: 'cats',
45+
limit: 5
46+
})).rejects.toThrow();
47+
expect(mockAxios).toHaveBeenCalledTimes(1);
48+
});
49+
50+
it('Should respect delay between retries', async function () {
51+
const startTime = Date.now();
52+
53+
// Mock sequence: 429 -> success
54+
mockAxios
55+
.mockRejectedValueOnce({ response: { status: 429 } })
56+
.mockResolvedValueOnce({ data: '<html>...</html>' });
57+
58+
await GOOGLE_IMG_SCRAP({
59+
search: 'cats',
60+
limit: 5
61+
});
62+
63+
const endTime = Date.now();
64+
const elapsedTime = endTime - startTime;
65+
66+
// Should have waited at least 1 second (initial delay)
67+
expect(elapsedTime).toBeGreaterThanOrEqual(1000);
68+
expect(mockAxios).toHaveBeenCalledTimes(2);
69+
});
70+
});

0 commit comments

Comments
 (0)