|
|
|
|
|
by crab_galaxy
488 days ago
|
|
Yeah to be fair testing a fetch request is not the best example right off the bat. That's an outlier IMO. That said it's very very easy to write similar looking code using react testing library as long as you're good about separating business logic into a hook. Where it gets dicy & hard to test is when components have complex state/effects co-mingling with render logic. Business logic is very easily testable as a hook, something like: ```
it('toggles switch state', () => {
const {current} = renderHook(() => useSwitchState); expect(current.checked).toBe(false);
current.toggle();
expect(current.state).toBe(nextState);
}
```Render logic is a bit different because React Testing Library's philosophy is to test as a user would interact with the UI, so that looks more like: ```
it('switches state on button click', () => {
render(<Switch onToggle={mockOnToggle} checked={false} />); getByRole('switch').click();
expect(mockOnToggle).toHaveBeenCalled();
});
``` |
|