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