Skip to content

Commit

Permalink
test: Use Sinon Fake Timer to Avoid Flaky Time Issue (#1667)
Browse files Browse the repository at this point in the history
* test: Use Sinon Fake Timer to Avoid Flaky Time Issue

* chore: change order for clarity
  • Loading branch information
d-goog authored Oct 11, 2023
1 parent d8e817b commit fad54d5
Showing 1 changed file with 18 additions and 2 deletions.
20 changes: 18 additions & 2 deletions test/test.util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -50,18 +61,23 @@ 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));
// back to the future 🏎️
sandbox.clock.tick(maxAge + 1);

// 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);
assert.equal(lru.get('third'), 3);
});
});
});

0 comments on commit fad54d5

Please sign in to comment.