|
1 | 1 | import React from 'react'; |
2 | | -import { render } from '@testing-library/react'; |
| 2 | +import { render, screen } from '@testing-library/react'; |
| 3 | +import userEvent from '@testing-library/user-event'; |
| 4 | +import { MemoryRouter } from 'react-router'; |
| 5 | +import fetchMock from 'jest-fetch-mock'; |
3 | 6 | import App from './App'; |
| 7 | +import mockResponse from './__mocks__/subreddit-reactjs-response.json'; |
4 | 8 |
|
5 | | -test('renders learn react link', () => { |
6 | | - const { getByText } = render(<App />); |
7 | | - const linkElement = getByText(/learn react/i); |
8 | | - expect(linkElement).toBeInTheDocument(); |
| 9 | +fetchMock.enableMocks(); |
| 10 | + |
| 11 | +function setup() { |
| 12 | + return render( |
| 13 | + <MemoryRouter> |
| 14 | + <App /> |
| 15 | + </MemoryRouter> |
| 16 | + ); |
| 17 | +} |
| 18 | + |
| 19 | +describe('Header', () => { |
| 20 | + test('"How it works" link points to the correct page', () => { |
| 21 | + setup(); |
| 22 | + |
| 23 | + const link = screen.getByRole('link', { name: /how it works/i }); |
| 24 | + userEvent.click(link); |
| 25 | + |
| 26 | + expect( |
| 27 | + screen.getByRole('heading', { name: /how it works/i }) |
| 28 | + ).toBeInTheDocument(); |
| 29 | + }); |
| 30 | +}); |
| 31 | + |
| 32 | +describe('Subreddit form', () => { |
| 33 | + test('loads posts and renders them on the page', async () => { |
| 34 | + fetch.once(JSON.stringify(mockResponse)); |
| 35 | + setup(); |
| 36 | + |
| 37 | + const subredditInput = screen.getByLabelText('r /'); |
| 38 | + userEvent.type(subredditInput, 'reactjs'); |
| 39 | + |
| 40 | + const submitButton = screen.getByRole('button', { name: /search/i }); |
| 41 | + userEvent.click(submitButton); |
| 42 | + |
| 43 | + expect(screen.getByText(/is loading/i)).toBeInTheDocument(); |
| 44 | + |
| 45 | + expect(await screen.findByText(/Number of top posts: 25/i)).toBeInTheDocument(); |
| 46 | + expect(fetch).toHaveBeenCalledWith('https://www.reddit.com/r/reactjs/top.json'); |
| 47 | + }); |
9 | 48 | }); |
0 commit comments