mardi 16 février 2021

Can't render initial React component in unit test router with query params

I am attempting to load my component with query params as these are necessary for certain actions, for example:

Component

// This component will be rendered when navigating to /my-comp

const MyComp = () => {
    // I am doing a console.log of all window.location elements here

    if (window.location.search) {
      return <Redirect to="/redirected />
    }


    return <SomeNonSearchComponent />
}

export default connect(mapStateToProps, mapDispatchToProps)(MyComponent);

Test

it('should render query component', () => {
    const mockStore = configureStore();
    const state = // some configured state
 
    const rendered = render(
        <Provider store={mockStore(state)}>
            <MemoryRouter initialEntries={[{ pathname: "/my-url", search: "?some=search" }]}>
                <MyComponent />
                <Route path="/redirected">Mock return body</Route>
            </MemoryRouter>
        </Provider>
    );

    // Rest of test
});

Test result When I run the test, I am getting a log of the window.location elements due to the console log shown above in the component, however the output I get of this seems to be:

{ 
    href: 'http://localhost/',
    origin: 'http://localhost',
    host: 'localhost',
    hostname: 'localhost',
    port: '',
    pathname: '/',
    search: '',
    hash: '' 
}

Am I doing something wrong in the setup to allow the component to see query params?

I was originally using a standard <Router>, however after reading a bit on the <MemoryRouter> it seemed there was the ability to use a search param to do this, but it doesn't seem to be having any affect.

Aucun commentaire:

Enregistrer un commentaire