Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to test Routes in react using jest and react testing library

so I'm trying to test each Route component and url are matching

the function

const App = () => (
    <Provider store={store}>
        <Router>
            <Layout>
                <Switch>
                    <Route exact path='/' component={HomePage} />
                    <Route exact path='/login' component={LoginPage} />
                    <Route exact path='/signup' component={SignupPage} />
                    <Route exact path='/recipes' component={RecipesPage} />
                    <Route exact path='/recipes/:id' component={RecipeDetailPage} />
                    <Route exact path='/reset_password' component={ResetPasswordPage} />
                    <Route exact path='/password/reset/confirm/:uid/:token' component={ResetPasswordConfirmPage} />
                    <Route component={NotFound} />
                </Switch>
            </Layout>
        </Router>
    </Provider>
);

anyone has an idea how can i test this?

like image 820
EliyaMelamed Avatar asked Sep 19 '25 04:09

EliyaMelamed


1 Answers

so after some trial and error I have managed to get the answer, this is the test that worked for me:

(i added a test-id to the homePage so i could know that this is the component that got rendered)

describe('App', () => {
    beforeEach(() => {
        const renderWithRouter = (ui, { route = '/' } = {}) => {
            window.history.pushState({}, 'Test page', route);

            return render(ui, { wrapper: BrowserRouter });
        };
        renderWithRouter(<App />);
    });
    afterEach(() => {
        cleanup();
    });
    test('should render without crashing', () => {});
    test('should render home page', () => {
        const homePage = screen.getByText('homePage');
        expect(homePage).toBeInTheDocument();
    });
});
like image 127
EliyaMelamed Avatar answered Sep 23 '25 01:09

EliyaMelamed