Skip to content

Commit

Permalink
Add msw testing
Browse files Browse the repository at this point in the history
  • Loading branch information
timomeh committed Feb 14, 2024
1 parent d80300a commit 50e5444
Show file tree
Hide file tree
Showing 8 changed files with 491 additions and 12 deletions.
18 changes: 18 additions & 0 deletions lib/WelcomeEmbed/TestComponentWithFetch.tsx
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 lib/WelcomeEmbed/__tests__/TestComponentWithFetch.test.tsx
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()
})
Loading

0 comments on commit 50e5444

Please sign in to comment.