Skip to content

Commit 749c94d

Browse files
authored
feat: add generic types support for render result queries (#566)
1 parent f31f4ae commit 749c94d

2 files changed

Lines changed: 25 additions & 2 deletions

File tree

projects/testing-library/src/lib/models.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import {
1111
} from '@angular/core';
1212
import { ComponentFixture, DeferBlockBehavior, DeferBlockState, TestBed } from '@angular/core/testing';
1313
import { Routes } from '@angular/router';
14-
import { BoundFunction, Queries, queries, Config as dtlConfig, PrettyDOMOptions } from '@testing-library/dom';
14+
import { BoundFunctions, Queries, queries, Config as dtlConfig, PrettyDOMOptions } from '@testing-library/dom';
1515

1616
// TODO: import from Angular (is a breaking change)
1717
interface OutputRef<T> {
@@ -29,7 +29,7 @@ export type OutputRefKeysWithCallback<T> = {
2929
: never;
3030
};
3131

32-
export type RenderResultQueries<Q extends Queries = typeof queries> = { [P in keyof Q]: BoundFunction<Q[P]> };
32+
export type RenderResultQueries<Q extends Queries = typeof queries> = BoundFunctions<Q>;
3333
export interface RenderResult<ComponentType, WrapperType = ComponentType> extends RenderResultQueries {
3434
/**
3535
* @description

projects/testing-library/src/tests/render.spec.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,29 @@ describe('DTL functionality', () => {
4545
// eslint-disable-next-line testing-library/prefer-screen-queries
4646
fireEvent.click(view.getByText('button'));
4747
});
48+
49+
test('render result queries should support generic type parameter', async () => {
50+
const view = await render(FixtureComponent);
51+
52+
// eslint-disable-next-line testing-library/prefer-screen-queries
53+
const inputByTestId: HTMLInputElement = view.getByTestId<HTMLInputElement>('input');
54+
expect(inputByTestId).toBeInTheDocument();
55+
56+
// screen.getByTestId should also accept a generic type parameter
57+
const inputByScreen: HTMLInputElement = screen.getByTestId<HTMLInputElement>('input');
58+
expect(inputByScreen).toBeInTheDocument();
59+
60+
// eslint-disable-next-line testing-library/prefer-screen-queries
61+
const button: HTMLButtonElement = view.getByRole<HTMLButtonElement>('button');
62+
expect(button).toBeInTheDocument();
63+
64+
// @ts-expect-error - generic narrows the type, so assigning HTMLInputElement to HTMLButtonElement should fail
65+
// eslint-disable-next-line testing-library/prefer-screen-queries
66+
const _wrongType: HTMLButtonElement = view.getByTestId<HTMLInputElement>('input');
67+
void _wrongType;
68+
69+
expect(true).toBeTruthy();
70+
});
4871
});
4972

5073
describe('components', () => {

0 commit comments

Comments
 (0)