File size: 17,218 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 |
import {
Component,
Injector,
computed,
effect,
input,
provideZonelessChangeDetection,
signal,
} from '@angular/core'
import { TestBed } from '@angular/core/testing'
import {
afterEach,
beforeEach,
describe,
expect,
expectTypeOf,
test,
vi,
} from 'vitest'
import { queryKey, sleep } from '@tanstack/query-test-utils'
import { QueryCache, QueryClient, injectQuery, provideTanStackQuery } from '..'
import { setSignalInputs } from './test-utils'
import type { CreateQueryOptions, OmitKeyof, QueryFunction } from '..'
describe('injectQuery', () => {
let queryCache: QueryCache
let queryClient: QueryClient
beforeEach(() => {
vi.useFakeTimers()
queryCache = new QueryCache()
queryClient = new QueryClient({ queryCache })
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
provideTanStackQuery(queryClient),
],
})
})
afterEach(() => {
vi.useRealTimers()
})
test('should return the correct types', () => {
const key = queryKey()
// unspecified query function should default to unknown
const noQueryFn = TestBed.runInInjectionContext(() =>
injectQuery(() => ({
queryKey: key,
})),
)
expectTypeOf(noQueryFn.data()).toEqualTypeOf<unknown>()
expectTypeOf(noQueryFn.error()).toEqualTypeOf<Error | null>()
// it should infer the result type from the query function
const fromQueryFn = TestBed.runInInjectionContext(() =>
injectQuery(() => ({
queryKey: key,
queryFn: () => 'test',
})),
)
expectTypeOf(fromQueryFn.data()).toEqualTypeOf<string | undefined>()
expectTypeOf(fromQueryFn.error()).toEqualTypeOf<Error | null>()
// it should be possible to specify the result type
const withResult = TestBed.runInInjectionContext(() =>
injectQuery<string>(() => ({
queryKey: key,
queryFn: () => 'test',
})),
)
expectTypeOf(withResult.data()).toEqualTypeOf<string | undefined>()
expectTypeOf(withResult.error()).toEqualTypeOf<Error | null>()
// it should be possible to specify the error type
type CustomErrorType = { message: string }
const withError = TestBed.runInInjectionContext(() =>
injectQuery<string, CustomErrorType>(() => ({
queryKey: key,
queryFn: () => 'test',
})),
)
expectTypeOf(withError.data()).toEqualTypeOf<string | undefined>()
expectTypeOf(withError.error()).toEqualTypeOf<CustomErrorType | null>()
// it should infer the result type from the configuration
const withResultInfer = TestBed.runInInjectionContext(() =>
injectQuery(() => ({
queryKey: key,
queryFn: () => true,
})),
)
expectTypeOf(withResultInfer.data()).toEqualTypeOf<boolean | undefined>()
expectTypeOf(withResultInfer.error()).toEqualTypeOf<Error | null>()
// it should be possible to specify a union type as result type
const unionTypeSync = TestBed.runInInjectionContext(() =>
injectQuery(() => ({
queryKey: key,
queryFn: () => (Math.random() > 0.5 ? ('a' as const) : ('b' as const)),
})),
)
expectTypeOf(unionTypeSync.data()).toEqualTypeOf<'a' | 'b' | undefined>()
const unionTypeAsync = TestBed.runInInjectionContext(() =>
injectQuery<'a' | 'b'>(() => ({
queryKey: key,
queryFn: () => Promise.resolve(Math.random() > 0.5 ? 'a' : 'b'),
})),
)
expectTypeOf(unionTypeAsync.data()).toEqualTypeOf<'a' | 'b' | undefined>()
// it should error when the query function result does not match with the specified type
TestBed.runInInjectionContext(() =>
// @ts-expect-error
injectQuery<number>(() => ({ queryKey: key, queryFn: () => 'test' })),
)
// it should infer the result type from a generic query function
/**
*
*/
function queryFn<T = string>(): Promise<T> {
return Promise.resolve({} as T)
}
const fromGenericQueryFn = TestBed.runInInjectionContext(() =>
injectQuery(() => ({
queryKey: key,
queryFn: () => queryFn(),
})),
)
expectTypeOf(fromGenericQueryFn.data()).toEqualTypeOf<string | undefined>()
expectTypeOf(fromGenericQueryFn.error()).toEqualTypeOf<Error | null>()
// todo use query options?
const fromGenericOptionsQueryFn = TestBed.runInInjectionContext(() =>
injectQuery(() => ({
queryKey: key,
queryFn: () => queryFn(),
})),
)
expectTypeOf(fromGenericOptionsQueryFn.data()).toEqualTypeOf<
string | undefined
>()
expectTypeOf(
fromGenericOptionsQueryFn.error(),
).toEqualTypeOf<Error | null>()
type MyData = number
type MyQueryKey = readonly ['my-data', number]
const getMyDataArrayKey: QueryFunction<MyData, MyQueryKey> = ({
queryKey: [, n],
}) => {
return n + 42
}
const fromMyDataArrayKeyQueryFn = TestBed.runInInjectionContext(() =>
injectQuery(() => ({
queryKey: ['my-data', 100] as const,
queryFn: getMyDataArrayKey,
})),
)
expectTypeOf(fromMyDataArrayKeyQueryFn.data()).toEqualTypeOf<
number | undefined
>()
// it should handle query-functions that return Promise<any>
const fromPromiseAnyQueryFn = TestBed.runInInjectionContext(() =>
injectQuery(() => ({
queryKey: key,
queryFn: () => fetch('return Promise<any>').then((resp) => resp.json()),
})),
)
expectTypeOf(fromPromiseAnyQueryFn.data()).toEqualTypeOf<any | undefined>()
TestBed.runInInjectionContext(() =>
effect(() => {
if (fromPromiseAnyQueryFn.isSuccess()) {
expect(fromMyDataArrayKeyQueryFn.data()).toBe(142)
}
}),
)
const getMyDataStringKey: QueryFunction<MyData, ['1']> = (context) => {
expectTypeOf(context.queryKey).toEqualTypeOf<['1']>()
return Number(context.queryKey[0]) + 42
}
const fromGetMyDataStringKeyQueryFn = TestBed.runInInjectionContext(() =>
injectQuery(() => ({
queryKey: ['1'] as ['1'],
queryFn: getMyDataStringKey,
})),
)
expectTypeOf(fromGetMyDataStringKeyQueryFn.data()).toEqualTypeOf<
number | undefined
>()
TestBed.runInInjectionContext(() =>
effect(() => {
if (fromGetMyDataStringKeyQueryFn.isSuccess()) {
expect(fromGetMyDataStringKeyQueryFn.data()).toBe(43)
}
}),
)
// handles wrapped queries with custom fetcher passed as inline queryFn
const createWrappedQuery = <
TQueryKey extends [string, Record<string, unknown>?],
TQueryFnData,
TError,
TData = TQueryFnData,
>(
qk: TQueryKey,
fetcher: (
obj: TQueryKey[1],
token: string,
// return type must be wrapped with TQueryFnReturn
) => Promise<TQueryFnData>,
options?: OmitKeyof<
CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
'queryKey' | 'queryFn' | 'initialData',
'safely'
>,
) =>
injectQuery(() => ({
queryKey: qk,
queryFn: () => fetcher(qk[1], 'token'),
...options,
}))
const fromWrappedQuery = TestBed.runInInjectionContext(() =>
createWrappedQuery([''], () => Promise.resolve('1')),
)
expectTypeOf(fromWrappedQuery.data()).toEqualTypeOf<string | undefined>()
// handles wrapped queries with custom fetcher passed directly to createQuery
const createWrappedFuncStyleQuery = <
TQueryKey extends [string, Record<string, unknown>?],
TQueryFnData,
TError,
TData = TQueryFnData,
>(
qk: TQueryKey,
fetcher: () => Promise<TQueryFnData>,
options?: OmitKeyof<
CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
'queryKey' | 'queryFn' | 'initialData',
'safely'
>,
) => injectQuery(() => ({ queryKey: qk, queryFn: fetcher, ...options }))
const fromWrappedFuncStyleQuery = TestBed.runInInjectionContext(() =>
createWrappedFuncStyleQuery([''], () => Promise.resolve(true)),
)
expectTypeOf(fromWrappedFuncStyleQuery.data()).toEqualTypeOf<
boolean | undefined
>()
})
test('should return pending status initially', () => {
const query = TestBed.runInInjectionContext(() => {
return injectQuery(() => ({
queryKey: ['key1'],
queryFn: () => sleep(10).then(() => 'Some data'),
}))
})
expect(query.status()).toBe('pending')
expect(query.isPending()).toBe(true)
expect(query.isFetching()).toBe(true)
expect(query.isStale()).toBe(true)
expect(query.isFetched()).toBe(false)
})
test('should resolve to success and update signal: injectQuery()', async () => {
const query = TestBed.runInInjectionContext(() => {
return injectQuery(() => ({
queryKey: ['key2'],
queryFn: () => sleep(10).then(() => 'result2'),
}))
})
await vi.advanceTimersByTimeAsync(11)
expect(query.status()).toBe('success')
expect(query.data()).toBe('result2')
expect(query.isPending()).toBe(false)
expect(query.isFetching()).toBe(false)
expect(query.isFetched()).toBe(true)
expect(query.isSuccess()).toBe(true)
})
test('should reject and update signal', async () => {
const query = TestBed.runInInjectionContext(() => {
return injectQuery(() => ({
retry: false,
queryKey: ['key3'],
queryFn: () =>
sleep(10).then(() => Promise.reject(new Error('Some error'))),
}))
})
await vi.advanceTimersByTimeAsync(11)
expect(query.status()).toBe('error')
expect(query.data()).toBe(undefined)
expect(query.error()).toMatchObject({ message: 'Some error' })
expect(query.isPending()).toBe(false)
expect(query.isFetching()).toBe(false)
expect(query.isError()).toBe(true)
expect(query.failureCount()).toBe(1)
expect(query.failureReason()).toMatchObject({ message: 'Some error' })
})
test('should update query on options contained signal change', async () => {
const key = signal(['key6', 'key7'])
const spy = vi.fn(() => sleep(10).then(() => 'Some data'))
const query = TestBed.runInInjectionContext(() => {
return injectQuery(() => ({
queryKey: key(),
queryFn: spy,
}))
})
await vi.advanceTimersByTimeAsync(0)
expect(spy).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(11)
expect(query.status()).toBe('success')
key.set(['key8'])
TestBed.tick()
expect(spy).toHaveBeenCalledTimes(2)
// should call queryFn with context containing the new queryKey
expect(spy).toBeCalledWith({
client: queryClient,
meta: undefined,
queryKey: ['key8'],
signal: expect.anything(),
})
})
test('should only run query once enabled signal is set to true', async () => {
const spy = vi.fn(() => sleep(10).then(() => 'Some data'))
const enabled = signal(false)
const query = TestBed.runInInjectionContext(() => {
return injectQuery(() => ({
queryKey: ['key9'],
queryFn: spy,
enabled: enabled(),
}))
})
expect(spy).not.toHaveBeenCalled()
expect(query.status()).toBe('pending')
enabled.set(true)
await vi.advanceTimersByTimeAsync(11)
expect(spy).toHaveBeenCalledTimes(1)
expect(query.status()).toBe('success')
})
test('should properly execute dependant queries', async () => {
const query1 = TestBed.runInInjectionContext(() => {
return injectQuery(() => ({
queryKey: ['dependant1'],
queryFn: () => sleep(10).then(() => 'Some data'),
}))
})
const dependentQueryFn = vi
.fn()
.mockImplementation(() => sleep(1000).then(() => 'Some data'))
const query2 = TestBed.runInInjectionContext(() => {
return injectQuery(
computed(() => ({
queryKey: ['dependant2'],
queryFn: dependentQueryFn,
enabled: !!query1.data(),
})),
)
})
expect(query1.data()).toStrictEqual(undefined)
expect(query2.fetchStatus()).toStrictEqual('idle')
expect(dependentQueryFn).not.toHaveBeenCalled()
await vi.advanceTimersByTimeAsync(11)
expect(query1.data()).toStrictEqual('Some data')
expect(query2.fetchStatus()).toStrictEqual('fetching')
await vi.advanceTimersByTimeAsync(1002)
expect(query2.fetchStatus()).toStrictEqual('idle')
expect(query2.status()).toStrictEqual('success')
expect(dependentQueryFn).toHaveBeenCalledTimes(1)
expect(dependentQueryFn).toHaveBeenCalledWith(
expect.objectContaining({ queryKey: ['dependant2'] }),
)
})
test('should use the current value for the queryKey when refetch is called', async () => {
const fetchFn = vi.fn(() => sleep(10).then(() => 'Some data'))
const keySignal = signal('key11')
const query = TestBed.runInInjectionContext(() => {
return injectQuery(() => ({
queryKey: ['key10', keySignal()],
queryFn: fetchFn,
enabled: false,
}))
})
expect(fetchFn).not.toHaveBeenCalled()
query.refetch().then(() => {
expect(fetchFn).toHaveBeenCalledTimes(1)
expect(fetchFn).toHaveBeenCalledWith(
expect.objectContaining({
queryKey: ['key10', 'key11'],
}),
)
})
await vi.advanceTimersByTimeAsync(11)
keySignal.set('key12')
TestBed.tick()
query.refetch().then(() => {
expect(fetchFn).toHaveBeenCalledTimes(2)
expect(fetchFn).toHaveBeenCalledWith(
expect.objectContaining({
queryKey: ['key10', 'key12'],
}),
)
})
await vi.advanceTimersByTimeAsync(11)
})
describe('throwOnError', () => {
test('should evaluate throwOnError when query is expected to throw', async () => {
const boundaryFn = vi.fn()
TestBed.runInInjectionContext(() => {
return injectQuery(() => ({
queryKey: ['key12'],
queryFn: () =>
sleep(10).then(() => Promise.reject(new Error('Some error'))),
retry: false,
throwOnError: boundaryFn,
}))
})
await vi.advanceTimersByTimeAsync(11)
expect(boundaryFn).toHaveBeenCalledTimes(1)
expect(boundaryFn).toHaveBeenCalledWith(
Error('Some error'),
expect.objectContaining({
state: expect.objectContaining({ status: 'error' }),
}),
)
})
test('should throw when throwOnError is true', async () => {
TestBed.runInInjectionContext(() => {
return injectQuery(() => ({
queryKey: ['key13'],
queryFn: () =>
sleep(0).then(() => Promise.reject(new Error('Some error'))),
throwOnError: true,
}))
})
await expect(vi.runAllTimersAsync()).rejects.toThrow('Some error')
})
test('should throw when throwOnError function returns true', async () => {
TestBed.runInInjectionContext(() => {
return injectQuery(() => ({
queryKey: ['key14'],
queryFn: () =>
sleep(0).then(() => Promise.reject(new Error('Some error'))),
throwOnError: () => true,
}))
})
await expect(vi.runAllTimersAsync()).rejects.toThrow('Some error')
})
})
test('should set state to error when queryFn returns reject promise', async () => {
const query = TestBed.runInInjectionContext(() => {
return injectQuery(() => ({
retry: false,
queryKey: ['key15'],
queryFn: () =>
sleep(10).then(() => Promise.reject(new Error('Some error'))),
}))
})
expect(query.status()).toBe('pending')
await vi.advanceTimersByTimeAsync(11)
expect(query.status()).toBe('error')
})
test('should render with required signal inputs', async () => {
@Component({
selector: 'app-fake',
template: `{{ query.data() }}`,
standalone: true,
})
class FakeComponent {
name = input.required<string>()
query = injectQuery(() => ({
queryKey: ['fake', this.name()],
queryFn: () => this.name(),
}))
}
const fixture = TestBed.createComponent(FakeComponent)
setSignalInputs(fixture.componentInstance, {
name: 'signal-input-required-test',
})
fixture.detectChanges()
await vi.advanceTimersByTimeAsync(0)
expect(fixture.componentInstance.query.data()).toEqual(
'signal-input-required-test',
)
})
describe('injection context', () => {
test('throws NG0203 with descriptive error outside injection context', () => {
expect(() => {
injectQuery(() => ({
queryKey: ['injectionContextError'],
queryFn: () => sleep(0).then(() => 'Some data'),
}))
}).toThrowError(/NG0203(.*?)injectQuery/)
})
test('can be used outside injection context when passing an injector', () => {
const query = injectQuery(
() => ({
queryKey: ['manualInjector'],
queryFn: () => sleep(0).then(() => 'Some data'),
}),
{
injector: TestBed.inject(Injector),
},
)
expect(query.status()).toBe('pending')
})
})
})
|