Wanderson Silva
Wanderson Silva

Reputation: 1199

react-router based app test

My application use react-router to manage user navigation and now I need add unit tests bu I'm stuck on how to change route.

My <App /> is (simplified):

class AppUser extends Component {
    render() {
        return (
            <div className="layout">
                {this.props.children}
            </div>
        );
    }
}

class Initial extends Component {
    render() {
        return (
            <div className="initial" />
        );
    }
}

export default class App extends Component {
    render() {
        let masterPageBase = (props) => (
            <AppUser>
                {props.children}
            </AppUser>
        );

        let notFound = () => (
            <div>
                <h1>Not found!</h1>
            </div>
        );

        <Router history={browserHistory}>
            <Route path="/" component={masterPageBase}>
                <IndexRoute component={Initial} />
                <Route path="*" component={notFound} />
            </Route>
        </Router>
    }
}

And my test is:

describe('<App />', () => {
    it('user', () => {
        const wrapper = shallow(<App />);

        // FIXME This fails
        expect(wrapper.find('AppUser').length).toEqual(1);
    });
});

How can I change the route so that will be an existing child.

Upvotes: 0

Views: 444

Answers (1)

Nicole
Nicole

Reputation: 1707

This is how you can fake a route in your tests:

There is a module called history which you can use to create a fake browser history in your tests. In order to apply it, you need to make your router parametric in the history it uses, like this:

export default class App extends Component {
    render() {
        createRouter(browserHistory);
    }
}

export function createRouter(history) {
    let masterPageBase = (props) => (
        <AppUser>
            {props.children}
        </AppUser>
    );

    let notFound = () => (
        <div>
            <h1>Not found!</h1>
        </div>
    );

    return <Router history={history}>
        <Route path="/" component={masterPageBase}>
            <IndexRoute component={Initial} />
            <Route path="*" component={notFound} />
        </Route>
    </Router>
}

In your tests, you can then use the history module to create a fake history:

import { useRouterHistory } from "react-router";
import createMemoryHistory from "history/lib/createMemoryHistory";

function navigatingTo(path) {
    return mount(createRouter(useRouterHistory(createMemoryHistory)(path)));
}

describe('Router', () => {
    it('user', () => {

        expect(navigatingTo("/").find('AppUser').length).toEqual(1);
    });
});

PS: If you run these tests in node.js then you need to make use of jsdom in order for enzyme's mount() to work.

Upvotes: 2

Related Questions