4

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?

1 Answer 1

2

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();
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Hi. I am using a react typescript app with react version ^17 and react-router v6 and getting Forbidden usage of render within a testing framework beforeEach setup

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.