我想在使用 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()
})
您可以导入
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();
});