<reponame>gaaangi-learning/enjoy-react<gh_stars>0
import * as React from 'react'
import { setupServer } from 'msw/node'
import { rest } from 'msw'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import Fetch from './fetch'

const server = setupServer(
    rest.get('/greeting', (req, res, ctx) => {
        return res(ctx.json({ greeting: 'Hello, world!' }))
    })
)

beforeAll(() => server.listen())
afterEach(() => server.resetHandlers())
afterAll(() => server.close())

describe('fetch', () => {
    test('loads and displays greeting', async () => {
        render(<Fetch url="/greeting" />)

        fireEvent.click(screen.getByText('Load Greeting'))
        await waitFor(() => screen.getByRole('heading'))

        expect(screen.getByRole('heading')).toHaveTextContent('Hello, world!')
        expect(screen.getByRole('button')).toBeDisabled()
    })

    test('handles server error', async () => {
        server.use(
            rest.get('/greeting', (req, res, ctx) => {
                return res(ctx.status(500))
            })
        )
        render(<Fetch url="/greeting" />)

        fireEvent.click(screen.getByText('Load Greeting'))
        await waitFor(() => screen.getByRole('alert'))

        expect(screen.getByRole('alert')).toHaveTextContent(
            'Oops, failed to fetch!'
        )
        expect(screen.getByRole('button')).not.toBeDisabled()
    })
})
