|
| 1 | +import React from 'react' |
| 2 | +import {render, cleanup} from 'react-testing-library' |
| 3 | +import { |
| 4 | + Router, |
| 5 | + Link, |
| 6 | + createHistory, |
| 7 | + createMemorySource, |
| 8 | + LocationProvider, |
| 9 | +} from '@reach/router' |
| 10 | +import 'jest-dom/extend-expect' |
| 11 | + |
| 12 | +const About = () => <div>You are on the about page</div> |
| 13 | +const Home = () => <div>You are home</div> |
| 14 | +const NoMatch = () => <div>No match</div> |
| 15 | + |
| 16 | +function App() { |
| 17 | + return ( |
| 18 | + <div> |
| 19 | + <Link to="/">Home</Link> |
| 20 | + <Link to="/about">About</Link> |
| 21 | + <Router> |
| 22 | + <Home path="/" /> |
| 23 | + <About path="/about" /> |
| 24 | + <NoMatch default /> |
| 25 | + </Router> |
| 26 | + </div> |
| 27 | + ) |
| 28 | +} |
| 29 | + |
| 30 | +// Ok, so here's what your tests might look like |
| 31 | + |
| 32 | +afterEach(cleanup) |
| 33 | + |
| 34 | +// this is a handy function that I would utilize for any component |
| 35 | +// that relies on the router being in context |
| 36 | +function renderWithRouter( |
| 37 | + ui, |
| 38 | + {route = '/', history = createHistory(createMemorySource(route))} = {}, |
| 39 | +) { |
| 40 | + return { |
| 41 | + ...render(<LocationProvider history={history}>{ui}</LocationProvider>), |
| 42 | + // adding `history` to the returned utilities to allow us |
| 43 | + // to reference it in our tests (just try to avoid using |
| 44 | + // this to test implementation details). |
| 45 | + history, |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +test('full app rendering/navigating', async () => { |
| 50 | + const { |
| 51 | + container, |
| 52 | + history: {navigate}, |
| 53 | + } = renderWithRouter(<App />) |
| 54 | + const appContainer = container |
| 55 | + // normally I'd use a data-testid, but just wanted to show this is also possible |
| 56 | + expect(appContainer.innerHTML).toMatch('You are home') |
| 57 | + |
| 58 | + // with reach-router we don't need to simulate a click event, we can just transition |
| 59 | + // to the page using the navigate function returned from the history object. |
| 60 | + await navigate('/about') |
| 61 | + expect(container.innerHTML).toMatch('You are on the about page') |
| 62 | +}) |
| 63 | + |
| 64 | +test('landing on a bad page', () => { |
| 65 | + const {container} = renderWithRouter(<App />, { |
| 66 | + route: '/something-that-does-not-match', |
| 67 | + }) |
| 68 | + // normally I'd use a data-testid, but just wanted to show this is also possible |
| 69 | + expect(container.innerHTML).toMatch('No match') |
| 70 | +}) |
0 commit comments