简体   繁体   中英

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?

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();
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM