|
1 | 1 | import {describe, expect, test} from "vitest"; |
2 | | -import {acquireLock, isLockActive, withLock} from "../src/index.js"; |
| 2 | +import {acquireLock, isLockActive, waitForLockRelease, withLock} from "../src/index.js"; |
3 | 3 |
|
4 | 4 | describe("withLock", () => { |
5 | 5 | test("lock works", async () => { |
@@ -103,4 +103,56 @@ describe("withLock", () => { |
103 | 103 |
|
104 | 104 | expect(res).toEqual([1, 2, 3]); |
105 | 105 | }); |
| 106 | + |
| 107 | + test("waitForLockRelease", async () => { |
| 108 | + const scope1 = {}; |
| 109 | + const key1 = "key"; |
| 110 | + |
| 111 | + const waitForEnoughMicrotasks = async () => { |
| 112 | + for (let i = 0; i < 10; i++) |
| 113 | + await Promise.resolve(); |
| 114 | + }; |
| 115 | + |
| 116 | + const lock1 = await acquireLock(scope1, key1); |
| 117 | + |
| 118 | + const lockWithError2 = withLock(scope1, key1, async () => { |
| 119 | + throw new Error("some error"); |
| 120 | + }); |
| 121 | + |
| 122 | + let lockReleased = false; |
| 123 | + void (async () => { |
| 124 | + await waitForLockRelease(scope1, key1); |
| 125 | + lockReleased = true; |
| 126 | + })(); |
| 127 | + |
| 128 | + const lock3Promise = acquireLock(scope1, key1); |
| 129 | + |
| 130 | + expect(lockReleased).toBe(false); |
| 131 | + await waitForEnoughMicrotasks(); |
| 132 | + expect(lockReleased).toBe(false); |
| 133 | + |
| 134 | + lock1.dispose(); |
| 135 | + expect(lockReleased).toBe(false); |
| 136 | + await waitForEnoughMicrotasks(); |
| 137 | + expect(lockReleased).toBe(false); |
| 138 | + |
| 139 | + try { |
| 140 | + await lockWithError2; |
| 141 | + expect.unreachable("lockWithError2 should throw"); |
| 142 | + } catch (err) { |
| 143 | + expect(lockReleased).toBe(false); |
| 144 | + await waitForEnoughMicrotasks(); |
| 145 | + expect(lockReleased).toBe(false); |
| 146 | + } |
| 147 | + |
| 148 | + const lock2 = await lock3Promise; |
| 149 | + expect(lockReleased).toBe(false); |
| 150 | + await waitForEnoughMicrotasks(); |
| 151 | + expect(lockReleased).toBe(false); |
| 152 | + |
| 153 | + lock2.dispose(); |
| 154 | + |
| 155 | + await waitForEnoughMicrotasks(); |
| 156 | + expect(lockReleased).toBe(true); |
| 157 | + }); |
106 | 158 | }); |
0 commit comments