Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the return type of a custom render for extending React Testing Library in test-utils using React/Typescript?

I'm not sure of the return type for the custom render function that uses Render of React Testing Library, I would've assumed it was element or JSX but that doesn't seem to work.

Code:

import React, { ReactElement } from 'react'
import { render, RenderOptions } from '@testing-library/react'
import { theme } from './theme'
import { ThemeProvider } from 'styled-components'
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import { searchReducer, initialState } from './store/reducer/searchReducer'

const store = createStore(searchReducer, initialState)

interface ProviderProps { 
  children?: NonNullable<React.ReactNode>
}

const TheProvider: React.FC<ProviderProps> = ({
  children,
}) => {
  return (
    <Provider store={store}>
      <ThemeProvider theme={theme}>
        { children }
      </ThemeProvider>
    </Provider>
  )
}

// here is the issue for function return type
const customRender= (
  ui: ReactElement,
  options?: Omit<RenderOptions, 'queries'>
) => render(ui, { wrapper: TheProvider, ...options })

export * from '@testing-library/react'

export { customRender as render }

like image 836
narliecholler Avatar asked Oct 19 '25 15:10

narliecholler


1 Answers

when I give the function the return type typeof render, it errors; Type 'RenderResult<typeof import("/path/node_modules/@testing-library/dom/types/queries"), HTMLElement>' is not assignable to type '{ <Q extends Queries = typeof import("/path/node_modules/@testing-library/dom/types/queries")

The return type of customRender would be ReturnType<typeof render> instead of just typeof render. That works, but you don't need to use typeof because you can import the correct type from the React Testing Library package. The type you want is RenderResult.

import { render, RenderOptions, RenderResult } from '@testing-library/react'
const customRender = (
  ui: ReactElement,
  options?: Omit<RenderOptions, "queries">
): RenderResult =>
  render(ui, { wrapper: TheProvider, ...options });
like image 152
Linda Paiste Avatar answered Oct 21 '25 07:10

Linda Paiste