DEV Community

grusingh
grusingh

Posted on • Updated on

Testing navigation in react

When testing navigation in a React component we can either check the final url or we can verify the updated DOM.

Test scenario 1: Test that clicking the about link will redirect to About Us path. This could be useful in scenarios where you are computing query params and want to assert on their values.

To make assertion on url possible we will have to use Router component (react-router-dom) with our own history object. Note that when using this approach the rendered markup won't get updated to reflect navigational changes.

Test scenario 2: Test that clicking the about link will render About Us path. This is preferred approach and useful in scenarios where DOM content changes after navigation.

To make assertions on updated DOM we will use BrowserRouter component (react-router-dom). Note that when this approach history won't be available to the test.

/* file: index.js */
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import {BrowserRouter} from "react-router-dom";

ReactDOM.render(
    <React.StrictMode>
        <BrowserRouter>
            <App/>
        </BrowserRouter>
    </React.StrictMode>,
    document.getElementById('root')
);

/* App.js */
import {Link, Route} from 'react-router-dom';

function App() {
    return <div>
        <h1>MyApp</h1>
        <nav>
            <ul>
                <li><Link to="/">Home</Link></li>
                <li><Link to="/about">About</Link></li>
            </ul>
        </nav>
        <div>
            <Route path="/" exact>
                <h2>Home page</h2>
            </Route>
            <Route path="/about">
                <h2>About Us</h2>
            </Route>
        </div>
    </div>
}

export default App;

/* App.spec.js */
import { render, screen} from '@testing-library/react';
import {BrowserRouter, Router} from 'react-router-dom';
import userEvent from "@testing-library/user-event";
import {createMemoryHistory} from 'history';
import App from './App';

test('should redirect and update history', () => {
    const history = createMemoryHistory();

    render(<Router history={history}><App/></Router>);

    userEvent.click(screen.getByText(/About/));

    expect(history.location.pathname).toEqual('/about');
});

test('should redirect and update dom', () => {
    render(<BrowserRouter><App/></BrowserRouter>);

    userEvent.click(screen.getByText(/About/));

    expect(screen.getByText(/About Us/i)).toBeInTheDocument();
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)