简体   繁体   中英

Return types for utility functions of React Testing Library

I'm trying to figure out what should the return type be (instead of generic: any) for the utilities returned by Testing Library React.

For example, with the following, I get TS error (Unexpected any. Specify a different type.)

const setup = (): any => {
              //~~~~~ Unexpected any. Specify a different type.
  const utils = render(
...
  );
  const button = utils.getByText(/some text/i);
  return { button, ...utils };
};
test('it renders', () => {
  const { button } = setup();
  expect(button).toBeInTheDocument();
});

setup returns an object of the type T which you need to find out. It has:

  • key: value where the name of the key is the string 'button' and value is typeof button which is JSX.Element .

  • All the keys and the values that are inside the type returned by render() . Which the spread operator injects directly into the type T. You didn't show the body of render() . I guess it returns also JSX.Element .

So we have

type T = {
  button: JSX.Element
  ...
  // the internals of JSX.Element that spread operator directly injects here
  ...
}

I had to give render() a body with sample code. And we have:

const render = (): JSX.Element => {
  const MyButton = () => ( <div>Hello </div> )
  return (
    <>
    <MyButton />
    </>
  )
};

type T = {
  type: any;
  props: any;
  key: string | number | null;
  button: JSX.Element;
};

const setup = (): T => {
  const utils = render();
  const button =  <div>Hello </div>;
  return { button, ...utils };
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM