Skip to content

Commit

Permalink
chore: use fake timers in tests
Browse files Browse the repository at this point in the history
  • Loading branch information
adamhamlin committed Jul 3, 2024
1 parent ee30ce7 commit 7e55493
Show file tree
Hide file tree
Showing 6 changed files with 41 additions and 24 deletions.
9 changes: 3 additions & 6 deletions tests/async/parallel.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,10 @@ import * as _ from 'radashi'
import { AggregateError } from 'radashi'

describe('parallel', () => {
beforeEach(() => {
vi.useFakeTimers({ shouldAdvanceTime: true })
})
test('returns all results from all functions', async () => {
const [errors, results] = await _.try(async () => {
return _.parallel(1, _.list(1, 3), async num => {
await _.sleep(1000)
await _.sleep(0)
return `hi_${num}`
})
})()
Expand All @@ -18,7 +15,7 @@ describe('parallel', () => {
test('throws errors as array of all errors', async () => {
const [error, results] = await _.try(async () => {
return _.parallel(1, _.list(1, 3), async num => {
await _.sleep(1000)
await _.sleep(0)
if (num === 2) {
throw new Error('number is 2')
}
Expand All @@ -36,7 +33,7 @@ describe('parallel', () => {
await _.parallel(3, _.list(1, 14), async () => {
numInProgress++
tracking.push(numInProgress)
await _.sleep(300)
await _.sleep(0)
numInProgress--
})
expect(Math.max(...tracking)).toBe(3)
Expand Down
16 changes: 12 additions & 4 deletions tests/async/retry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const cast = <T = RetryOptions>(value: any): T => value

describe('retry', () => {
beforeEach(() => {
vi.useFakeTimers({ shouldAdvanceTime: true })
vi.useFakeTimers()
})
test('returns result of given function', async () => {
const result = await _.retry(cast(null), async _bail => {
Expand Down Expand Up @@ -69,7 +69,9 @@ describe('retry', () => {
const func = async () => {
throw 'quitagain'
}
await _.retry({ delay: 100 }, func)
const promise = _.retry({ delay: 1000, times: 2 }, func)
vi.advanceTimersByTimeAsync(1000)
await promise
} catch (err) {
expect(err).toBe('quitagain')
return
Expand All @@ -80,7 +82,7 @@ describe('retry', () => {
let count = 0
let backoffs = 0
const start = Date.now()
await _.retry(
const promise = _.retry(
{
times: 3,
backoff: i => {
Expand All @@ -95,13 +97,19 @@ describe('retry', () => {
}
},
)
// Two async advances for the first two async attempts, each of which are
// followed by sleeps
vi.advanceTimersToNextTimerAsync()
vi.advanceTimersToNextTimerAsync()
await promise

const diff = Date.now() - start
expect(count).toBe(3)
// Time taken should at least be the
// total ms backed off. Using exponential
// backoff (above) 3 times (passing on
// the third try) that is:
// - 10**1 + 10**2 = 1025
// - 1**10 + 2**10 = 1025
// The performance typically comes in 1
// or 2 milliseconds after.
expect(diff).toBeGreaterThanOrEqual(backoffs)
Expand Down
6 changes: 4 additions & 2 deletions tests/async/sleep.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@ import * as _ from 'radashi'

describe('sleep', () => {
beforeEach(() => {
vi.useFakeTimers({ shouldAdvanceTime: true })
vi.useFakeTimers()
})
test('suspends a thread for a specified number of milliseconds', async () => {
const ONE_SECOND = 1000
const before = Date.now()
await _.sleep(ONE_SECOND)
const promise = _.sleep(ONE_SECOND)
vi.advanceTimersToNextTimerAsync()
await promise
const after = Date.now()
expect(after).toBeGreaterThanOrEqual(before + ONE_SECOND)
})
Expand Down
14 changes: 8 additions & 6 deletions tests/curry/debounce.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,11 @@ describe('debounce', () => {
func()
func()
}
const delay = 600

beforeEach(() => {
func = _.debounce({ delay: 600 }, mockFunc)
vi.useFakeTimers()
func = _.debounce({ delay }, mockFunc)
})

afterEach(() => {
Expand All @@ -21,7 +23,7 @@ describe('debounce', () => {
test('only executes once when called rapidly', async () => {
runFunc3Times()
expect(mockFunc).toHaveBeenCalledTimes(0)
await _.sleep(610)
vi.advanceTimersByTime(delay + 10)
expect(mockFunc).toHaveBeenCalledTimes(1)
})

Expand All @@ -47,7 +49,7 @@ describe('debounce', () => {
expect(mockFunc).toHaveBeenCalledTimes(1)
func()
expect(mockFunc).toHaveBeenCalledTimes(1)
await _.sleep(610)
vi.advanceTimersByTime(delay + 10)
expect(mockFunc).toHaveBeenCalledTimes(2)
func.flush()
expect(mockFunc).toHaveBeenCalledTimes(3)
Expand All @@ -58,19 +60,19 @@ describe('debounce', () => {
func()
results.push(func.isPending())
results.push(func.isPending())
await _.sleep(610)
vi.advanceTimersByTime(delay + 10)
results.push(func.isPending())
func()
results.push(func.isPending())
await _.sleep(610)
vi.advanceTimersByTime(delay + 10)
results.push(func.isPending())
assert.deepEqual(results, [true, true, false, true, false])
})

test('returns if there is any pending invocation when the pending method is called', async () => {
func()
func.cancel()
await _.sleep(610)
vi.advanceTimersByTime(delay + 10)
expect(mockFunc).toHaveBeenCalledTimes(0)
})
})
6 changes: 4 additions & 2 deletions tests/curry/memo.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,20 +24,22 @@ describe('memo', () => {
expect(resultB).not.toBe(resultA)
})
test('calls function again when first value expires', async () => {
vi.useFakeTimers()
const func = _.memo(() => new Date().getTime(), {
ttl: 1,
})
const resultA = func()
await new Promise(res => setTimeout(res, 100))
vi.advanceTimersByTime(100)
const resultB = func()
expect(resultA).not.toBe(resultB)
})
test('does not call function again when first value has not expired', async () => {
vi.useFakeTimers()
const func = _.memo(() => new Date().getTime(), {
ttl: 1000,
})
const resultA = func()
await new Promise(res => setTimeout(res, 100))
vi.advanceTimersByTime(100)
const resultB = func()
expect(resultA).toBe(resultB)
})
Expand Down
14 changes: 10 additions & 4 deletions tests/curry/throttle.test.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,20 @@
import * as _ from 'radashi'

describe('throttle', () => {
const interval = 600

beforeEach(() => {
vi.useFakeTimers()
})

test('throttles!', async () => {
let calls = 0
const func = _.throttle({ interval: 600 }, () => calls++)
const func = _.throttle({ interval }, () => calls++)
func()
func()
func()
expect(calls).toBe(1)
await _.sleep(610)
vi.advanceTimersByTime(interval + 10)
func()
func()
func()
Expand All @@ -17,15 +23,15 @@ describe('throttle', () => {

test('returns if the throttle is active', async () => {
const results = []
const func = _.throttle({ interval: 600 }, () => {})
const func = _.throttle({ interval }, () => {})
results.push(func.isThrottled())
func()
results.push(func.isThrottled())
func()
results.push(func.isThrottled())
func()
results.push(func.isThrottled())
await _.sleep(610)
vi.advanceTimersByTime(interval + 10)
results.push(func.isThrottled())
assert.deepEqual(results, [false, true, true, true, false])
})
Expand Down

0 comments on commit 7e55493

Please sign in to comment.