|
1 | 1 | import { retry } from "./retry";
|
2 | 2 |
|
3 | 3 | describe("retry", () => {
|
| 4 | + const successMsg = "Success"; |
| 5 | + const errorMsg = "Expected failure"; |
| 6 | + const retries = 10; |
| 7 | + const retryable = jest.fn().mockRejectedValue(errorMsg); |
| 8 | + |
| 9 | + afterEach(() => { |
| 10 | + jest.clearAllMocks(); |
| 11 | + }); |
| 12 | + |
4 | 13 | it("should retry a function the specified number of times", async () => {
|
5 |
| - const retries = 10; |
6 |
| - const retryable = jest.fn().mockRejectedValue("Expected failure"); |
| 14 | + await expect(retry(retryable, retries)).rejects.toStrictEqual(errorMsg); |
| 15 | + expect(retryable).toHaveBeenCalledTimes(retries + 1); |
| 16 | + }); |
7 | 17 |
|
8 |
| - await retry(retryable, retries).catch(msg => { |
9 |
| - expect(retryable.mock.calls.length).toEqual(retries + 1); |
10 |
| - expect(msg).toEqual("Expected failure"); |
11 |
| - }); |
| 18 | + it("should not retry if successful", async () => { |
| 19 | + retryable.mockResolvedValueOnce(successMsg); |
| 20 | + await expect(retry(retryable, retries)).resolves.toStrictEqual(successMsg); |
| 21 | + expect(retryable).toHaveBeenCalledTimes(1); |
12 | 22 | });
|
13 | 23 |
|
14 | 24 | it("should stop retrying after the first successful invocation", async () => {
|
15 |
| - const retries = 10; |
16 | 25 | const successfulInvocationIndex = 3;
|
17 |
| - let invocations = 0; |
18 |
| - const retryable = jest.fn(() => { |
19 |
| - if (++invocations === successfulInvocationIndex) { |
20 |
| - return Promise.resolve("Success!"); |
21 |
| - } |
22 |
| - return Promise.reject("Expected failure"); |
23 |
| - }); |
| 26 | + for (let i = 1; i < successfulInvocationIndex; i++) { |
| 27 | + retryable.mockRejectedValueOnce(errorMsg); |
| 28 | + } |
| 29 | + retryable.mockResolvedValueOnce(successMsg); |
24 | 30 |
|
25 |
| - await retry(retryable, retries).then(() => { |
26 |
| - expect(retryable.mock.calls.length).toEqual(successfulInvocationIndex); |
27 |
| - }); |
| 31 | + await expect(retry(retryable, retries)).resolves.toStrictEqual(successMsg); |
| 32 | + expect(retryable).toHaveBeenCalledTimes(successfulInvocationIndex); |
28 | 33 | });
|
29 | 34 | });
|
0 commit comments