Skip to content
Merged
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
52 changes: 52 additions & 0 deletions packages/query-core/src/__tests__/utils.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { QueryClient } from '..'
import {
addToEnd,
addToStart,
ensureQueryFn,
hashKey,
hashQueryKeyByOptions,
isPlainArray,
Expand All @@ -14,8 +15,10 @@ import {
replaceEqualDeep,
shallowEqualObjects,
shouldThrowError,
skipToken,
} from '../utils'
import { Mutation } from '../mutation'
import type { QueryFunctionContext } from '..'

describe('core/utils', () => {
describe('hashQueryKeyByOptions', () => {
Expand Down Expand Up @@ -534,6 +537,55 @@ describe('core/utils', () => {
})
})

describe('ensureQueryFn', () => {
const context = {} as QueryFunctionContext

it('should return a function that resolves to initialPromise when queryFn is missing and initialPromise is provided', async () => {
const initialPromise = Promise.resolve('initial-data')

const resolved = ensureQueryFn(
{ queryHash: '["key"]' },
{ initialPromise },
)

await expect(resolved(context)).resolves.toBe('initial-data')
})

it('should return a function that rejects when initialPromise rejects', async () => {
const error = new Error('initial-promise-error')
const initialPromise = Promise.reject(error)

const resolved = ensureQueryFn(
{ queryHash: '["key"]' },
{ initialPromise },
)

await expect(resolved(context)).rejects.toBe(error)
})

it('should return a function that rejects with missing queryFn error when queryFn is set to skipToken', async () => {
const consoleErrorSpy = vi
.spyOn(console, 'error')
.mockImplementation(() => undefined)

const resolved = ensureQueryFn({
queryFn: skipToken,
queryHash: '["skip"]',
})

expect(consoleErrorSpy).toHaveBeenCalledWith(
expect.stringContaining(
'Attempted to invoke queryFn when set to skipToken',
),
)
await expect(resolved(context)).rejects.toThrow(
'Missing queryFn: \'["skip"]\'',
)

consoleErrorSpy.mockRestore()
})
})

describe('shouldThrowError', () => {
it('should return the result of executing throwOnError if throwOnError parameter is a function', () => {
const throwOnError = (error: Error) => error.message === 'test error'
Expand Down
Loading