Test BrowserRouter in React by pushing url

Viewed 176

I'm trying to write some tests where I mock a click button and I check if I can reach the right page. I would like to "reset" the render by pushing the url in the way history.push('/'); to redirect to main page after every test. I was thinking to have something like

afterEach(() => {
    history.push('/');
})

I split my code in two files to make it more readable.

App.test.js

import '@testing-library/jest-dom';
import {render, screen} from '@testing-library/react';
import App from "../App";
import {clickButton, waitForPage} from "./Functions";

beforeEach(() => {
    render(<App/>);
})

afterEach(() => {
    history.push('/');
})

test('Cookies banner is visible', () => {
    const bannerText = screen.getByText(/This website uses cookies/i);
    expect(bannerText).toBeInTheDocument();
})

test('Routing web page test', async () => {
    const road = [
        ['site design', 'How this works'],
        ['my story', 'Born curious'],
        ['contact', 'Please leave a message'],
        ['games', 'metal'],
        ['trivial', 'Set up your game'],
        ['web cams', 'Web Cam Of The Day'],
        ['radio', 'media player'],
        ['movies', 'movie platform'],
        ['weather','is going in my'],
        ['recipes', 'cooking']
    ]

    await waitForPage('manciotech');
    clickButton('enter');
    await waitForPage('site design');
    for (const comb of road) {
        clickButton(comb[0]);
        await waitForPage(comb[1]);
        clickButton('go back');
    }
},10000)


test('Not connected pages', async () => {
    await waitForPage('site design');
    clickButton('my projects');
    await waitForPage('go back');
    expect(window.location.pathname).toBe('/boo');
})

Functions.js

import {screen, waitFor} from "@testing-library/react";

export const waitForPage = async function (name) {
    await waitFor(() => {
        expect(screen.getByText(new RegExp(name, "i"))).toBeInTheDocument();
    })
}

export const clickCookiesConsent = function (){
    screen.getByRole('button', {name: /accept/i}).click();
}

export const clickButton = function (name){
    const enter = screen.getByRole('button', {name: new RegExp(name, 'i')});
    enter.click();
}

I followed many tutorials but nothing works. I tried with <Router> and the history hook, using windows.location ecc...

Seam like I'm having problem because I'm using BrowserRouter instead of Router. I wrote my App code using Browser due to the limitation I encountered building the app in different way, but this end in a blind way.... if I cannot test anymore....

here my full code https://github.com/mancio/MancioTechWeb

Tnx for help.

1 Answers

The browser router doesn’t accept a history prop. As you mentioned, in order to do it that way, you could use the normal React Router.

Have you tried using <Redirect to={'/'}> ?

Related