Skip to content

Commit

Permalink
fix(vitest): improve vi.waitUntil type to excude falsy types (#4572)
Browse files Browse the repository at this point in the history
  • Loading branch information
sheremet-va authored Nov 22, 2023
1 parent 0a14dd8 commit 2365230
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
6 changes: 4 additions & 2 deletions packages/vitest/src/integrations/wait.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,12 +100,14 @@ export type WaitUntilCallback<T> = () => T | Promise<T>

export interface WaitUntilOptions extends Pick<WaitForOptions, 'interval' | 'timeout'> {}

type Truthy<T> = T extends false | '' | 0 | null | undefined ? never : T

export function waitUntil<T>(callback: WaitUntilCallback<T>, options: number | WaitUntilOptions = {}) {
const { setTimeout, setInterval, clearTimeout, clearInterval } = getSafeTimers()
const { interval = 50, timeout = 1000 } = typeof options === 'number' ? { timeout: options } : options
const STACK_TRACE_ERROR = new Error('STACK_TRACE_ERROR')

return new Promise<T>((resolve, reject) => {
return new Promise<Truthy<T>>((resolve, reject) => {
let promiseStatus: 'idle' | 'pending' | 'resolved' | 'rejected' = 'idle'
let timeoutId: ReturnType<typeof setTimeout>
let intervalId: ReturnType<typeof setInterval>
Expand All @@ -125,7 +127,7 @@ export function waitUntil<T>(callback: WaitUntilCallback<T>, options: number | W
if (intervalId)
clearInterval(intervalId)

resolve(result)
resolve(result as Truthy<T>)
return true
}

Expand Down
16 changes: 16 additions & 0 deletions test/typescript/test-d/vi.test-d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { expectTypeOf, test, vi } from 'vitest'

test('vi.waitUntil correctly resolves return type', () => {
expectTypeOf(vi.waitUntil(() => 'string')).resolves.toEqualTypeOf<string>()
expectTypeOf(vi.waitUntil(() => 1)).resolves.toEqualTypeOf<number>()

expectTypeOf(vi.waitUntil(() => false as const)).resolves.toEqualTypeOf<never>()
expectTypeOf(vi.waitUntil(() => '' as const)).resolves.toEqualTypeOf<never>()
expectTypeOf(vi.waitUntil(() => 0 as const)).resolves.toEqualTypeOf<never>()

expectTypeOf(vi.waitUntil(() => '' as '' | number)).resolves.toEqualTypeOf<number>()
expectTypeOf(vi.waitUntil(() => null as null | number)).resolves.toEqualTypeOf<number>()
expectTypeOf(vi.waitUntil(() => undefined as undefined | number)).resolves.toEqualTypeOf<number>()
expectTypeOf(vi.waitUntil(() => false as false | number)).resolves.toEqualTypeOf<number>()
expectTypeOf(vi.waitUntil(() => 0 as 0 | string)).resolves.toEqualTypeOf<string>()
})

0 comments on commit 2365230

Please sign in to comment.