Skip to content

Commit b881482

Browse files
committed
test(query-core/utils): add tests for 'ensureQueryFn' initialPromise fallback and skipToken handling
1 parent 5b5d1db commit b881482

1 file changed

Lines changed: 53 additions & 0 deletions

File tree

packages/query-core/src/__tests__/utils.test.tsx

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { QueryClient } from '..'
44
import {
55
addToEnd,
66
addToStart,
7+
ensureQueryFn,
78
hashKey,
89
hashQueryKeyByOptions,
910
isPlainArray,
@@ -14,6 +15,7 @@ import {
1415
replaceEqualDeep,
1516
shallowEqualObjects,
1617
shouldThrowError,
18+
skipToken,
1719
} from '../utils'
1820
import { Mutation } from '../mutation'
1921

@@ -534,6 +536,57 @@ describe('core/utils', () => {
534536
})
535537
})
536538

539+
describe('ensureQueryFn', () => {
540+
it('should return a function that resolves to initialPromise when queryFn is missing and initialPromise is provided', async () => {
541+
const initialPromise = Promise.resolve('initial-data')
542+
543+
const resolved = ensureQueryFn(
544+
{ queryHash: '["key"]' },
545+
{ initialPromise },
546+
)
547+
548+
await expect(
549+
(resolved as unknown as () => Promise<string>)(),
550+
).resolves.toBe('initial-data')
551+
})
552+
553+
it('should return a function that rejects when initialPromise rejects', async () => {
554+
const error = new Error('initial-promise-error')
555+
const initialPromise = Promise.reject(error)
556+
557+
const resolved = ensureQueryFn(
558+
{ queryHash: '["key"]' },
559+
{ initialPromise },
560+
)
561+
562+
await expect(
563+
(resolved as unknown as () => Promise<unknown>)(),
564+
).rejects.toBe(error)
565+
})
566+
567+
it('should return a function that rejects with missing queryFn error when queryFn is set to skipToken', async () => {
568+
const consoleErrorSpy = vi
569+
.spyOn(console, 'error')
570+
.mockImplementation(() => undefined)
571+
572+
const resolved = ensureQueryFn({
573+
queryFn: skipToken,
574+
queryHash: '["skip"]',
575+
})
576+
577+
expect(consoleErrorSpy).toHaveBeenCalledWith(
578+
expect.stringContaining(
579+
'Attempted to invoke queryFn when set to skipToken',
580+
),
581+
)
582+
await expect(
583+
(resolved as unknown as () => Promise<unknown>)(),
584+
).rejects.toThrow('Missing queryFn: \'["skip"]\'')
585+
586+
consoleErrorSpy.mockRestore()
587+
})
588+
})
589+
537590
describe('shouldThrowError', () => {
538591
it('should return the result of executing throwOnError if throwOnError parameter is a function', () => {
539592
const throwOnError = (error: Error) => error.message === 'test error'

0 commit comments

Comments
 (0)