Loading Thucde.dev
Preparing the next view.
import {render, screen} from '@testing-library/react', import the component to be tested, probably do some kinds of event or pass in mock data and test.import { render, screen } from '@testing-library/react'; import MyComponent from '@/MyComponent'; describe('test MyComponent', () => { const mockData = {john: "doe"}; it('should render correctly', async () => { // Act render(<MyComponent data={mockData} />); // Assert await waitFor(() => { expect(screen.getByText(mockData.john)).toBeInTheDocument(); }); }); })
An example on how to test a React component with React Testing Library
import userEvent from '@testing-library/user-event' [...] render(<MyComponent data={mockData} />); await userEvent.click(screen.getByText('doe')) await waitFor(() => { // assuming there's a button with the button text is "doe", // and that button is disabled on clicked. expect(screen.getByRole('button')).toBeDisabled() }); [...]
Trigger a user click event with @testing-library/user-event
import { render } from '@testing-library/react'; import ProviderA from '@/providerA'; import WrapperB from '@/wrapperB'; import ThemeC from '@/themeC'; const TestContext = ({children}: PropsWithChildren) => { // do something if needed return ( <ProviderA> <WrapperB> <ThemeC> {children} </ThemeC> </WrapperB> </ProviderA> ) } const renderWithContext = (component: ReactComponent, options = {}) => { return render(component, { wrapper: TestContext, ...options }); } export * from '@testing-library/react'; export {renderWithContext as render};
Twist the render function
@testing-library/react, we import them from our previously created file, such as import { render, screen } from '@/test/utils';. Now the rendered component has the context it supposed to have.