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

test-utils.ts

77 lines2.3 KB

1import { isSignal, untracked } from '@angular/core'
2import { SIGNAL, signalSetFn } from '@angular/core/primitives/signals'
3import { expect } from 'vitest'
4import type { InputSignal, Signal } from '@angular/core'
5import type { ComponentFixture } from '@angular/core/testing'
6​
7// Evaluate all signals on an object and return the result
8function evaluateSignals<T extends Record<string, any>>(
9 obj: T,
10): { [K in keyof T]: ReturnType<T[K]> } {
11 const result: Partial<{ [K in keyof T]: ReturnType<T[K]> }> = {}
12​
13 untracked(() => {
14 for (const key in obj) {
15 if (
16 Object.prototype.hasOwnProperty.call(obj, key) &&
17 // Only evaluate signals, not normal functions
18 isSignal(obj[key])
19 ) {
20 const func = obj[key]
21 result[key] = func()
22 }
23 }
24 })
25​
26 return result as { [K in keyof T]: ReturnType<T[K]> }
28​
29export const expectSignals = <T extends Record<string, any>>(
30 obj: T,
31 expected: Partial<{
32 [K in keyof T]: T[K] extends Signal<any> ? ReturnType<T[K]> : never
33 }>,
34): void => {
35 expect(evaluateSignals(obj)).toMatchObject(expected)
37​
38type ToSignalInputUpdatableMap<T> = {
39 [K in keyof T as T[K] extends InputSignal<any>
40 ? K
41 : never]: T[K] extends InputSignal<infer Value> ? Value : never
43​
44function componentHasSignalInputProperty<TProperty extends string>(
45 component: object,
46 property: TProperty,
47): component is { [key in TProperty]: InputSignal<unknown> } {
48 return (
49 component.hasOwnProperty(property) && (component as any)[property][SIGNAL]
50 )
52​
53/**
54 * Set required signal input value to component fixture
55 * @see https://github.com/angular/angular/issues/54013
56 */
57export function setSignalInputs<T extends NonNullable<unknown>>(
58 component: T,
59 inputs: ToSignalInputUpdatableMap<T>,
60) {
61 for (const inputKey in inputs) {
62 if (componentHasSignalInputProperty(component, inputKey)) {
63 signalSetFn(component[inputKey][SIGNAL], inputs[inputKey])
64 }
65 }
67​
68export function setFixtureSignalInputs<T extends NonNullable<unknown>>(
69 componentFixture: ComponentFixture<T>,
70 inputs: ToSignalInputUpdatableMap<T>,
71 options: { detectChanges: boolean } = { detectChanges: true },
72) {
73 setSignalInputs(componentFixture.componentInstance, inputs)
74 if (options.detectChanges) {
75 componentFixture.detectChanges()
76 }