Skip to content

Commit 8b04fbe

Browse files
edward-simpsonisaacs
authored andcommitted
doc: guidance re mocking timers for testing TTL
Added testing guidelines for TTL-related functionality. PR-URL: #385 Credit: @edward-simpson Close: #385 Reviewed-by: @isaacs EDIT(@isaacs): also add mention of `perf` option to override time tracking entirely, regardless of framework.
1 parent 83b51a7 commit 8b04fbe

1 file changed

Lines changed: 49 additions & 0 deletions

File tree

README.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -295,6 +295,55 @@ If performance matters to you:
295295
has been made to make the performance impact minimal, but it
296296
isn't nothing.
297297

298+
## Testing
299+
300+
When writing tests that involve TTL-related functionality, note
301+
that this module creates an internal reference to the global
302+
`performance` or `Date` objects at import time. If you import it
303+
statically at the top level, those references cannot be mocked or
304+
overridden in your test environment.
305+
306+
To avoid this, dynamically import the package within your tests
307+
so that the references are captured after your mocks are applied.
308+
For example:
309+
310+
```ts
311+
// ❌ Not recommended
312+
import { LRUCache } from 'lru-cache'
313+
// mocking timers, e.g. jest.useFakeTimers()
314+
315+
// ✅ Recommended for TTL tests
316+
// mocking timers, e.g. jest.useFakeTimers()
317+
const { LRUCache } = await import('lru-cache')
318+
```
319+
320+
This ensures that your mocked timers or time sources are
321+
respected when testing TTL behavior.
322+
323+
Additionally, you can pass in a `perf` option when creating your
324+
LRUCache instance. This option accepts any object with a `now`
325+
method that returns a number.
326+
327+
For example, this would be a very bare-bones time-mocking system
328+
you could use in your tests, without any particular test
329+
framework:
330+
331+
```ts
332+
import { LRUCache } from 'lru-cache'
333+
334+
let myClockTime = 0
335+
336+
const cache = new LRUCache<string>({
337+
max: 10,
338+
ttl: 1000,
339+
perf: {
340+
now: () => myClockTime,
341+
},
342+
})
343+
344+
// run tests, updating myClockTime as needed
345+
```
346+
298347
## Breaking Changes in Version 7
299348

300349
This library changed to a different algorithm and internal data

0 commit comments

Comments
 (0)