React-router: Testing Guidance Using Typescript/Jest

Created on 31 Oct 2017  路  2Comments  路  Source: ReactTraining/react-router

Does anyone have examples of how to test react components that also inject the router props. I've tried just passing in null for those, but my tests seem to fail.

I cannot seem to figure out what to pass in for the props that are injected by react router.

Most helpful comment

I figured it out and will post here for others would have trouble testing with react router 4 and typescript:

Create a mock router:

`import { RouteComponentProps } from 'react-router'
import { match } from 'react-router-dom';
import {UnregisterCallback, Href} from 'history'

//This is to mock out the dependencies for react router
export function getMockRouterProps<P>(data: P) {

    var location: {
            hash: "",
            key: "",
            pathname: "",
            search: "",
            state: {}
        };

    var props: RouteComponentProps<P> = {
    match: {
            isExact: true,
            params: data,
            path: "",
            url: ""
        },
        location: location,
        history: {
            length:2,
            action:"POP",
            location: location,
            push: () => {},
            replace: () => {},
            go: (num) => {},
            goBack: () => {},
            goForward: () => {},
            block: (t) => {
                var temp: UnregisterCallback = null;
                return temp;
            },
            createHref: (t) => {
                var temp: Href = "";
                return temp;
            },
            listen: (t) => {
                var temp: UnregisterCallback = null;
                return temp;
            }

        },
        staticContext: {
        }
    };


    return props;
}`

Then use as follows:

`
import {getMockRouterProps} from '../__test_helper__/ReactRouterHelper'

describe('>>>My First Test',()=>{
    var todos: Test[] = [];

    var routerProps = getMockRouterProps<ReduxTestComponentProps>(null);

    it('+++ Make sure that clicking add todo calls redux', () => {
        const mockTodoAddDispatch = jest.fn();

        const mockTodoDeleteDispatch = jest.fn();

        const wrapper = mount<ReduxTestComponent, ReduxTestComponentState>(
                <ReduxTestComponent
                    history={routerProps.history}
                    location={routerProps.location}
                    match={routerProps.match}
                    todos={todos}
                    addTodoActionDispatch={() => mockTodoAddDispatch()}
                    deleteTodoActionDispatch={() => mockTodoDeleteDispatch()}
                    />
          );

        var state: ReduxTestComponentState = {
            text: "Hello"
        };

        wrapper.setState(state);

        const addTodoButton = wrapper.find('#redux-add-btn');

        addTodoButton.simulate("click");

        expect(mockTodoAddDispatch.mock.calls.length).toBe(1);
        expect(mockTodoDeleteDispatch.mock.calls.length).toBe(0);
    });`

All 2 comments

This is a bug tracker, not a support system. For usage questions, please use Stack Overflow or Reactiflux where there are a lot more people ready to help you out. Thanks!

I figured it out and will post here for others would have trouble testing with react router 4 and typescript:

Create a mock router:

`import { RouteComponentProps } from 'react-router'
import { match } from 'react-router-dom';
import {UnregisterCallback, Href} from 'history'

//This is to mock out the dependencies for react router
export function getMockRouterProps<P>(data: P) {

    var location: {
            hash: "",
            key: "",
            pathname: "",
            search: "",
            state: {}
        };

    var props: RouteComponentProps<P> = {
    match: {
            isExact: true,
            params: data,
            path: "",
            url: ""
        },
        location: location,
        history: {
            length:2,
            action:"POP",
            location: location,
            push: () => {},
            replace: () => {},
            go: (num) => {},
            goBack: () => {},
            goForward: () => {},
            block: (t) => {
                var temp: UnregisterCallback = null;
                return temp;
            },
            createHref: (t) => {
                var temp: Href = "";
                return temp;
            },
            listen: (t) => {
                var temp: UnregisterCallback = null;
                return temp;
            }

        },
        staticContext: {
        }
    };


    return props;
}`

Then use as follows:

`
import {getMockRouterProps} from '../__test_helper__/ReactRouterHelper'

describe('>>>My First Test',()=>{
    var todos: Test[] = [];

    var routerProps = getMockRouterProps<ReduxTestComponentProps>(null);

    it('+++ Make sure that clicking add todo calls redux', () => {
        const mockTodoAddDispatch = jest.fn();

        const mockTodoDeleteDispatch = jest.fn();

        const wrapper = mount<ReduxTestComponent, ReduxTestComponentState>(
                <ReduxTestComponent
                    history={routerProps.history}
                    location={routerProps.location}
                    match={routerProps.match}
                    todos={todos}
                    addTodoActionDispatch={() => mockTodoAddDispatch()}
                    deleteTodoActionDispatch={() => mockTodoDeleteDispatch()}
                    />
          );

        var state: ReduxTestComponentState = {
            text: "Hello"
        };

        wrapper.setState(state);

        const addTodoButton = wrapper.find('#redux-add-btn');

        addTodoButton.simulate("click");

        expect(mockTodoAddDispatch.mock.calls.length).toBe(1);
        expect(mockTodoDeleteDispatch.mock.calls.length).toBe(0);
    });`
Was this page helpful?
0 / 5 - 0 ratings

Related issues

stnwk picture stnwk  路  3Comments

imWildCat picture imWildCat  路  3Comments

yormi picture yormi  路  3Comments

alexyaseen picture alexyaseen  路  3Comments

ackvf picture ackvf  路  3Comments