vendredi 12 février 2021

Unit testing - You should not use

I'm receiving the error

Invariant failed: You should not use <Redirect> outside a <Router>

when I am attempting to unit test my <Redirect> and I can't seem to solve the reason why...

index.js

import { Route } from 'react-router-dom';
import { Provider } from 'react-redux';
import { ConnectedRouter } from 'connected-react-router';
...
ReactDOM.render((
    <Provider store={store}>
      <ConnectedRouter history={history}>
          <Route path={process.env.PUBLIC_URL} component={App} />
      </ConnectedRouter>
    </Provider>
), document.getElementById('root'));

App.jsx

import { Switch, Router, Route, Redirect, withRouter } from 'react-router-dom';
...
class App extends Component {
    render() {
        return (
            <div class="content">
                <Router>
                    <Switch>
                        <Route 
                            path={`${process.env.PUBLIC_URL}/my-path`} 
                            render={MyComponent}
                        />
                        ...
                    </Switch>
                </Router>
            </div>
        )
    }
}

// I omitted the map(States/Dispatch)ToProps as they aren't important here
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(App));

MyComponent.jsx

import {Redirect} from "react-router-dom";
...
const MyComponent = (/* { some props here } */) => {

    // Redirect to /login if toggle active
    // /login will render the Login component within the app
    if (redirect) {
        return <Redirect to={`${process.env.PUBLIC_URL}/login`}/>;
    }

    // If redirecting, show the good component
    return <SomeOtherComponent />
}

// not included mapStateToProps as it's not important here
export default connect(mapStateToProps)(MyComponent);

Testing I understand that I am needing to add a provider and a router to capture everything, but it seems that I just can't get it working, throwing the Invariant failed error whenever I try anything...

Is there something I'm missing?

import {BrowserRouter, Router} from "react-router-dom"
import {Provider} from "react-redux";
...
it('Should redirect', async () => {
    const state = configState(/* set initial state */);
    const store = configureStore();
    const history = createMemoryHistory()

    const rendered = render(
        <Provider store={store(state)}>
            <BrowserRouter>
                <MyComponent />
            </BrowserRouter>
        </Provider>
    );

    // check that the content changed to the new page
    expect(rendered.getByText('login-title')).toBeTruthy();

Aucun commentaire:

Enregistrer un commentaire