Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

utils.tsx

74 lines1.8 KB

1import * as utils from '@tanstack/query-core'
2import { act, render } from '@testing-library/preact'
3import type { ComponentChildren, VNode } from 'preact'
4import { useEffect, useState } from 'preact/hooks'
5import { vi } from 'vitest'
6import type { MockInstance } from 'vitest'
7​
8import { QueryClientProvider, onlineManager } from '..'
9import type { QueryClient } from '..'
10​
11export function renderWithClient(
12 client: QueryClient,
13 ui: VNode,
14): ReturnType<typeof render> {
15 const { rerender, ...result } = render(
16 <QueryClientProvider client={client}>{ui}</QueryClientProvider>,
17 )
18 return {
19 ...result,
20 rerender: (rerenderUi: VNode) =>
21 rerender(
22 <QueryClientProvider client={client}>{rerenderUi}</QueryClientProvider>,
23 ),
24 } as any
26​
27export function Blink({
28 duration,
29 children,
30}: {
31 duration: number
32 children: ComponentChildren
33}) {
34 const [shouldShow, setShouldShow] = useState<boolean>(true)
35​
36 useEffect(() => {
37 setShouldShow(true)
38 const timeout = setActTimeout(() => setShouldShow(false), duration)
39 return () => {
40 clearTimeout(timeout)
41 }
42 }, [duration, children])
43​
44 return shouldShow ? <>{children}</> : <>off</>
46​
47export function mockOnlineManagerIsOnline(
48 value: boolean,
49): MockInstance<() => boolean> {
50 return vi.spyOn(onlineManager, 'isOnline').mockReturnValue(value)
52​
53export function setActTimeout(fn: () => void, ms?: number) {
54 return setTimeout(() => {
55 act(() => {
56 fn()
57 })
58 }, ms)
60​
61// This monkey-patches the isServer-value from utils,
62// so that we can pretend to be in a server environment
63export function setIsServer(isServer: boolean) {
64 const original = utils.isServer
65 Object.defineProperty(utils, 'isServer', {
66 get: () => isServer,
67 })
68​
69 return () => {
70 Object.defineProperty(utils, 'isServer', {
71 get: () => original,
72 })
73 }