-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
8 changed files
with
491 additions
and
12 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
import { useEffect, useState } from 'preact/hooks' | ||
|
||
// This is just an example to illustrate tests working with fetch | ||
export function TestComponentWithFetch({ id = 'abc' }) { | ||
const [name, setName] = useState<string>('') | ||
|
||
useEffect(() => { | ||
fetch(`https://api.example.com/users/${id}`) | ||
.then((res) => res.json()) | ||
.then((user) => setName(user.name)) | ||
}, [id]) | ||
|
||
if (!name) { | ||
return <div>Loading</div> | ||
} | ||
|
||
return <div>Hello, {name}</div> | ||
} |
26 changes: 26 additions & 0 deletions
26
lib/WelcomeEmbed/__tests__/TestComponentWithFetch.test.tsx
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
import { render, screen } from '@testing-library/preact' | ||
|
||
import { http, HttpResponse, server } from '@/testing/http' | ||
|
||
import { TestComponentWithFetch } from '../TestComponentWithFetch' | ||
|
||
it('greets the default user from the api', async () => { | ||
render(<TestComponentWithFetch />) | ||
|
||
expect(screen.getByText('Loading')).toBeInTheDocument() | ||
expect(await screen.findByText(/Hello, George/i)).toBeInTheDocument() | ||
}) | ||
|
||
it('allows api overrides', async () => { | ||
server.use( | ||
// Be careful to only override unique handler URLs and not default handlers, | ||
// as it can otherwise affect concurrent tests. | ||
http.get('https://api.example.com/users/elaine-123', () => { | ||
return HttpResponse.json({ name: 'Elaine' }) | ||
}), | ||
) | ||
render(<TestComponentWithFetch id="elaine-123" />) | ||
|
||
expect(screen.getByText('Loading')).toBeInTheDocument() | ||
expect(await screen.findByText(/Hello, Elaine/i)).toBeInTheDocument() | ||
}) |
Oops, something went wrong.