Created
February 11, 2026 18:53
-
-
Save claudiainbytes/d7f3e72150519ad7a80070a238967c10 to your computer and use it in GitHub Desktop.
Testing de useEffect y Side Effects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Component | |
| const UserProfile = ({ userId }) => { | |
| const [user, setUser] = useState(null) | |
| const [loading, setLoading] = useState(true) | |
| useEffect(() => { | |
| const fetchUser = async () => { | |
| setLoading(true) | |
| const response = await fetch(`/api/users/${userId}`) | |
| const data = await response.json() | |
| setUser(data) | |
| setLoading(false) | |
| } | |
| fetchUser() | |
| }, [userId]) | |
| if (loading) return <div>Loading...</div> | |
| return <div>User: {user.name}</div> | |
| } | |
| // Test | |
| describe('UserProfile', () => { | |
| it('carga usuario al montar', async () => { | |
| server.use( | |
| http.get('/api/users/:id', () => { | |
| return HttpResponse.json({ id: 1, name: 'John Doe' }) | |
| }) | |
| ) | |
| render(<UserProfile userId={1} />) | |
| expect(screen.getByText(/loading/i)).toBeInTheDocument() | |
| expect(await screen.findByText('User: John Doe')).toBeInTheDocument() | |
| }) | |
| it('recarga cuando cambia userId', async () => { | |
| server.use( | |
| http.get('/api/users/1', () => { | |
| return HttpResponse.json({ id: 1, name: 'John Doe' }) | |
| }), | |
| http.get('/api/users/2', () => { | |
| return HttpResponse.json({ id: 2, name: 'Jane Smith' }) | |
| }) | |
| ) | |
| const { rerender } = render(<UserProfile userId={1} />) | |
| expect(await screen.findByText('User: John Doe')).toBeInTheDocument() | |
| rerender(<UserProfile userId={2} />) | |
| expect(await screen.findByText('User: Jane Smith')).toBeInTheDocument() | |
| }) | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment