Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test: use fake timers in tests #69

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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