Skip to content

refactor: stronger typing of inputs #473

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Aug 3, 2024
43 changes: 42 additions & 1 deletion projects/testing-library/src/lib/models.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Type, DebugElement, OutputRef, EventEmitter } from '@angular/core';
import { Type, DebugElement, OutputRef, EventEmitter, Signal } from '@angular/core';
import { ComponentFixture, DeferBlockBehavior, DeferBlockState, TestBed } from '@angular/core/testing';
import { Routes } from '@angular/router';
import { BoundFunction, Queries, queries, Config as dtlConfig, PrettyDOMOptions } from '@testing-library/dom';
Expand Down Expand Up @@ -78,6 +78,29 @@ export interface RenderResult<ComponentType, WrapperType = ComponentType> extend
renderDeferBlock: (deferBlockState: DeferBlockState, deferBlockIndex?: number) => Promise<void>;
}

declare const ALIASED_INPUT_BRAND: unique symbol;
export type AliasedInput<T> = T & {
[ALIASED_INPUT_BRAND]: T;
};
export type AliasedInputs = Record<string, AliasedInput<unknown>>;

export type ComponentInput<T> =
| {
[P in keyof T]?: T[P] extends Signal<infer U>
? U // If the property is a Signal, apply Partial to the inner type
: Partial<T[P]>; // Otherwise, apply Partial to the property itself
}
| AliasedInputs;

/**
* @description
* Creates an aliased input branded type with a value
*
*/
export function aliasedInputWithValue<T>(value: T): AliasedInput<T> {
return value as AliasedInput<T>;
}

export interface RenderComponentOptions<ComponentType, Q extends Queries = typeof queries> {
/**
* @description
Expand Down Expand Up @@ -199,6 +222,7 @@ export interface RenderComponentOptions<ComponentType, Q extends Queries = typeo
* @description
* An object to set `@Input` properties of the component
*
* @deprecated use the `inputs` option instead. When you need to use aliases, use the `aliasedInputWithValue(...)` helper function.
* @default
* {}
*
Expand All @@ -210,6 +234,23 @@ export interface RenderComponentOptions<ComponentType, Q extends Queries = typeo
* })
*/
componentInputs?: Partial<ComponentType> | { [alias: string]: unknown };

/**
* @description
* An object to set `@Input` or `input()` properties of the component
*
* @default
* {}
*
* @example
* await render(AppComponent, {
* inputs: {
* counterValue: 10,
* someAlias: aliasedInputWithValue('value')
* }
*/
inputs?: ComponentInput<ComponentType>;

/**
* @description
* An object to set `@Output` properties of the component
Expand Down
7 changes: 5 additions & 2 deletions projects/testing-library/src/lib/testing-library.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ export async function render<SutType, WrapperType = SutType>(
componentProperties = {},
componentInputs = {},
componentOutputs = {},
inputs: newInputs = {},
on = {},
componentProviders = [],
childComponentOverrides = [],
Expand Down Expand Up @@ -176,8 +177,10 @@ export async function render<SutType, WrapperType = SutType>(

let detectChanges: () => void;

const allInputs = { ...componentInputs, ...newInputs };

let renderedPropKeys = Object.keys(componentProperties);
let renderedInputKeys = Object.keys(componentInputs);
let renderedInputKeys = Object.keys(allInputs);
let renderedOutputKeys = Object.keys(componentOutputs);
let subscribedOutputs: SubscribedOutput<SutType>[] = [];

Expand Down Expand Up @@ -224,7 +227,7 @@ export async function render<SutType, WrapperType = SutType>(
return createdFixture;
};

const fixture = await renderFixture(componentProperties, componentInputs, componentOutputs, on);
const fixture = await renderFixture(componentProperties, allInputs, componentOutputs, on);

if (deferBlockStates) {
if (Array.isArray(deferBlockStates)) {
Expand Down
46 changes: 45 additions & 1 deletion projects/testing-library/tests/render.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,12 @@ import {
ElementRef,
inject,
output,
input,
} from '@angular/core';
import { outputFromObservable } from '@angular/core/rxjs-interop';
import { NoopAnimationsModule, BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { TestBed } from '@angular/core/testing';
import { render, fireEvent, screen, OutputRefKeysWithCallback } from '../src/public_api';
import { render, fireEvent, screen, OutputRefKeysWithCallback, aliasedInputWithValue } from '../src/public_api';
import { ActivatedRoute, Resolve, RouterModule } from '@angular/router';
import { fromEvent, map } from 'rxjs';
import { AsyncPipe, NgIf } from '@angular/common';
Expand Down Expand Up @@ -533,3 +534,46 @@ describe('configureTestBed', () => {
expect(configureTestBedFn).toHaveBeenCalledTimes(1);
});
});

describe('inputs and signals', () => {
@Component({
selector: 'atl-fixture',
template: `<span>{{ myName() }}</span> <span>{{ myJob() }}</span>`,
})
class InputComponent {
myName = input('foo');

myJob = input('bar', { alias: 'job' });
}

it('should set the input component', async () => {
await render(InputComponent, {
inputs: {
myName: 'Bob',
job: aliasedInputWithValue('Builder'),
},
});

expect(screen.getByText('Bob')).toBeInTheDocument();
expect(screen.getByText('Builder')).toBeInTheDocument();
});

it('should typecheck correctly', async () => {
// @ts-expect-error - myName is a string
await render(InputComponent, {
inputs: {
myName: 123,
},
});

// @ts-expect-error - job is not using aliasedInputWithValue
await render(InputComponent, {
inputs: {
job: 'not used with aliasedInputWithValue',
},
});

// add a statement so the test succeeds
expect(true).toBeTruthy();
});
});