From d06e979d544d858e0c4a64cf38ff4c591b6917f0 Mon Sep 17 00:00:00 2001 From: Daniel Bankhead Date: Wed, 11 Oct 2023 11:52:00 -0700 Subject: [PATCH 1/2] test: Use Sinon Fake Timer to Avoid Flaky Time Issue --- test/test.util.ts | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/test/test.util.ts b/test/test.util.ts index 6871c621..e92babf5 100644 --- a/test/test.util.ts +++ b/test/test.util.ts @@ -13,10 +13,21 @@ // limitations under the License. import {strict as assert} from 'assert'; +import * as sinon from 'sinon'; import {LRUCache} from '../src/util'; describe('util', () => { + let sandbox: sinon.SinonSandbox; + + beforeEach(() => { + sandbox = sinon.createSandbox(); + }); + + afterEach(() => { + sandbox.restore(); + }); + describe('LRUCache', () => { it('should set and get a cached item', () => { const expected = 'value'; @@ -50,17 +61,22 @@ describe('util', () => { it('should evict items older than a supplied `maxAge`', async () => { const maxAge = 50; + sandbox.clock = sinon.useFakeTimers(); + const lru = new LRUCache({capacity: 5, maxAge}); lru.set('first', 1); lru.set('second', 2); - await new Promise(res => setTimeout(res, maxAge + 1)); - - lru.set('third', 3); + // back to the future 🏎️ + sandbox.clock.tick(maxAge + 1); + // these are too old assert.equal(lru.get('first'), undefined); assert.equal(lru.get('second'), undefined); + + // just set, so should be fine + lru.set('third', 3); assert.equal(lru.get('third'), 3); }); }); From 8c13c3b281b32b944759b78e7c42e27c49e86bc6 Mon Sep 17 00:00:00 2001 From: Daniel Bankhead Date: Wed, 11 Oct 2023 12:01:44 -0700 Subject: [PATCH 2/2] chore: change order for clarity --- test/test.util.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test/test.util.ts b/test/test.util.ts index e92babf5..6f584c9c 100644 --- a/test/test.util.ts +++ b/test/test.util.ts @@ -71,13 +71,13 @@ describe('util', () => { // back to the future 🏎️ sandbox.clock.tick(maxAge + 1); - // these are too old - assert.equal(lru.get('first'), undefined); - assert.equal(lru.get('second'), undefined); - // just set, so should be fine lru.set('third', 3); assert.equal(lru.get('third'), 3); + + // these are too old + assert.equal(lru.get('first'), undefined); + assert.equal(lru.get('second'), undefined); }); }); });