如何在 RTL 测试中使用 React Redux useDispatch 钩子?

问题描述 投票:0回答:1

我想在使用 redux 调度后测试 React 组件。我正在使用“test-utils.ts”文件中的自定义渲染函数:

import { ReactElement } from 'react'
import { render, RenderOptions } from '@testing-library/react'

import { Provider } from 'react-redux'
import { store } from './store/store'
import AppTheme from './theme/AppTheme'

type childrenType = {
    children?: string | JSX.Element | JSX.Element[] | undefined
}

const Providers = ({ children }: childrenType) => {
    return (
        <Provider store={store}>
            <AppTheme>
                {children}
            </AppTheme>
        </Provider>
    )
}

const customRender = (
    ui: ReactElement,
    options?: Omit<RenderOptions, 'wrapper'>

) => render(ui, { wrapper: Providers, ...options })

export * from '@testing-library/react'
export { customRender as render }

现在我想在测试中渲染组件之前调度一个操作来更改状态。

test('renders files section', () => {
    // Do something to dispatch an action...

    render(<ContentSection />)

    const headerElement = screen.getByRole('heading', { level: 2, name: 'Files:' })
    expect(headerElement).toBeInTheDocument()
})
reactjs typescript redux react-testing-library
1个回答
0
投票

您可以导入

store
对象并使用它来向其分派操作,例如
store.dispatch

它可能类似于以下示例:

import { act, render } from 'test-utils';
import { store } from './store/store';

test('renders files section', () => {
  render(<ContentSection />);

  act(() => {
    store.dispatch(/* action to dispatch */);
  });

  const headerElement = screen.getByRole('heading', { level: 2, name: 'Files:' });
  expect(headerElement).toBeInTheDocument();
});
© www.soinside.com 2019 - 2024. All rights reserved.