test: add missing tests/utils/AsyncLock.test.ts file
authorJérôme Benoit <jerome.benoit@piment-noir.org>
Sat, 3 Aug 2024 13:14:51 +0000 (15:14 +0200)
committerJérôme Benoit <jerome.benoit@piment-noir.org>
Sat, 3 Aug 2024 13:14:51 +0000 (15:14 +0200)
Signed-off-by: Jérôme Benoit <jerome.benoit@piment-noir.org>
src/utils/AsyncLock.ts
tests/utils/AsyncLock.test.ts [new file with mode: 0644]

index f69faac80d77a907704adfc9574b8711bb41e2c8..eef006dbbe96cb93b9a505383924b33d9be14014 100644 (file)
@@ -51,10 +51,8 @@ export class AsyncLock {
       asyncLock.acquired = false
       return
     }
-    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-    const queuedResolve = asyncLock.resolveQueue.dequeue()!
     await new Promise<void>(resolve => {
-      queuedResolve()
+      asyncLock.resolveQueue.dequeue()
       resolve()
     })
   }
diff --git a/tests/utils/AsyncLock.test.ts b/tests/utils/AsyncLock.test.ts
new file mode 100644 (file)
index 0000000..dbec498
--- /dev/null
@@ -0,0 +1,42 @@
+import { describe, it } from 'node:test'
+
+import { expect } from 'expect'
+
+import { AsyncLock, AsyncLockType } from '../../src/utils/AsyncLock.js'
+
+await describe('AsyncLock test suite', async () => {
+  await it('Verify runExclusive()', () => {
+    const runs = 10
+    let executed: number[] = []
+    let count = 0
+    const fn = () => {
+      executed.push(++count)
+    }
+    for (let i = 0; i < runs; i++) {
+      AsyncLock.runExclusive(AsyncLockType.configuration, fn)
+        .then(() => {
+          expect(executed).toEqual(new Array(count).fill(0).map((_, i) => ++i))
+          return undefined
+        })
+        // eslint-disable-next-line @typescript-eslint/use-unknown-in-catch-callback-variable
+        .catch(console.error)
+    }
+    executed = []
+    count = 0
+    const asyncFn = async () => {
+      await new Promise(resolve => {
+        setTimeout(resolve, 100)
+      })
+      executed.push(++count)
+    }
+    for (let i = 0; i < runs; i++) {
+      AsyncLock.runExclusive(AsyncLockType.configuration, asyncFn)
+        .then(() => {
+          expect(executed).toEqual(new Array(count).fill(0).map((_, i) => ++i))
+          return undefined
+        })
+        // eslint-disable-next-line @typescript-eslint/use-unknown-in-catch-callback-variable
+        .catch(console.error)
+    }
+  })
+})