Skip to content

Commit

Permalink
Expose custom return type for our mount function
Browse files Browse the repository at this point in the history
  • Loading branch information
acelaya committed Dec 19, 2024
1 parent bc6ae96 commit 1776ee9
Showing 1 changed file with 48 additions and 4 deletions.
52 changes: 48 additions & 4 deletions src/mount.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as enzyme from 'enzyme';
import type { ReactWrapper } from 'enzyme';
import type { VNode } from 'preact';
import { FunctionComponent, JSX, VNode } from 'preact';

let containers: HTMLElement[] = [];
let wrappers: ReactWrapper[] = [];
Expand All @@ -20,16 +20,60 @@ export type MountOptions = {
prepareContainer?: (container: HTMLElement) => void;
};

export type EnzymeSelector = string | FunctionComponent<any>;

/**
* Inspired by DefinitelyTyped's ReactWrapper.
* @see https://github.com/DefinitelyTyped/DefinitelyTyped/blob/cebb88fecfa52f854826e216a537867c11b0150e/types/enzyme/index.d.ts
*/
export type ComponentWrapper<P = {}, S = {}> = {
at(index: number): ComponentWrapper;

childAt(index: number): ComponentWrapper<any, any>;
childAt<P2, S2>(index: number): ComponentWrapper<P2, S2>;

closest<P2>(component: FunctionComponent<P2>): ComponentWrapper<P2, any>;
closest(selector: string): ComponentWrapper<JSX.HTMLAttributes, any>;

exists(selector?: EnzymeSelector): boolean;

find<P2>(component: FunctionComponent<P2>): ComponentWrapper<P2, any>;
find(selector: string): ComponentWrapper<JSX.HTMLAttributes, any>;

first(): ComponentWrapper<P, S>;
forEach(
fn: (wrapper: ComponentWrapper<P, S>, index: number) => any,
): ComponentWrapper<P, S>;
getDOMNode(): HTMLElement;
hasClass(className: string | RegExp): boolean;
last(): ComponentWrapper<P, S>;
length: number;
map<V>(fn: (wrapper: ComponentWrapper<P, S>, index: number) => V): V[];

prop<K extends keyof P>(key: K): P[K];
prop<T>(key: string): T;

props(): P;
setProps<K extends keyof P>(
props: Pick<P, K>,
callback?: () => void,
): ComponentWrapper<P, S>;
simulate(event: string, ...args: any[]): ComponentWrapper<P, S>;
text(): string;
unmount(): void;
update(): ComponentWrapper<P, S>;
};

/**
* Render a Preact component using Enzyme and return a wrapper.
*
* The component can be unmounted by calling `wrapper.unmount()` or by calling
* {@link unmountAll} at the end of the test.
*/
export function mount(
export function mount<P = {}, S = {}>(
jsx: VNode,
{ connected = false, prepareContainer }: MountOptions = {},
) {
): ComponentWrapper<P, S> {
let wrapper;
if (connected) {
const container = document.createElement('div');
Expand All @@ -46,7 +90,7 @@ export function mount(

wrappers.push(wrapper);

return wrapper;
return wrapper as ComponentWrapper<P, S>;
}

/**
Expand Down

0 comments on commit 1776ee9

Please sign in to comment.