如何使用RouteComponentProps测试React组件?

Ser*_*rov 18 testing typescript reactjs jestjs react-router

我有一个组件,其中包含扩展的道具,RouteComponentProps如下所示:

export interface RouteComponentProps<P> {
  match: match<P>;
  location: H.Location;
  history: H.History;
  staticContext?: any;
}
Run Code Online (Sandbox Code Playgroud)

现在,当我在应用程序中使用我的组件时,我将这些道具传递给它:

<MyComponent
    match={this.props.match}
    location={this.props.location}
    history={this.props.history}
/>
Run Code Online (Sandbox Code Playgroud)

道具已经可用,因为它在反应路由器内部运行.

现在,我怎么没有测试这个组件match,location,history可用?

我需要模拟它们还是应该以某种方式自动加载一些辅助函数?

Dav*_*ker 13

为了回答您的最后一个问题,建议的方法是<MemoryRouter>< *your component here* ></MemoryRouter>在测试中使用。Typescript不会接受此组件会将所需的属性传递给您的组件,因此,我认为这不是一种类型安全的方法。

这是针对React Router v4的,不适用于以前的版本。

对于一种类型安全的方法来测试HOC包装的组件,withRouter您可以通过react-router和history包构建位置,历史记录和匹配项。

本示例使用了酶和快照测试,但可以轻松进行任何其他测试。

这避免了我需要<MemoryRouter>用作打字稿不喜欢的包装器。

// Other imports here
import { createMemoryHistory, createLocation } from 'history';
import { match } from 'react-router';

const history = createMemoryHistory();
const path = `/route/:id`;

const match: match<{ id: string }> = {
    isExact: false,
    path,
    url: path.replace(':id', '1'),
    params: { id: "1" }
};

const location = createLocation(match.url);

test('shallow render', () => {
    const wrapper = shallow(
        <MyComponent history={history}
                     location={location}
                     match={match} />
    );

    expect(wrapper).toMatchSnapshot();
});
Run Code Online (Sandbox Code Playgroud)

注意不要使用它来测试实现细节,这可能很诱人,但是如果您要重构,它将给您带来很多痛苦。

为此提供帮助可能是使此功能可重复使用的最佳方法。

import { createLocation, createMemoryHistory } from 'history';
import { match as routerMatch } from 'react-router';

type MatchParameter<Params> = { [K in keyof Params]?: string };

export const routerTestProps = <Params extends MatchParameter<Params> = {}>
    (path: string, params: Params, extendMatch: Partial<routerMatch<any>> = {}) => {
        const match: routerMatch<Params> = Object.assign({}, {
            isExact: false,
            path,
            url: generateUrl(path, params),
            params
        }, extendMatch);
        const history = createMemoryHistory();
        const location = createLocation(match.url);

        return { history, location, match };
    };


const generateUrl = <Params extends MatchParameter<Params>>
    (path: string, params: Params): string => {
        let tempPath = path;

        for (const param in params) {
            if (params.hasOwnProperty(param)) {
                const value = params[param];
                tempPath = tempPath.replace(
                    `:${param}`, value as NonNullable<typeof value>
                );
            }
        }

        return tempPath;
    };
Run Code Online (Sandbox Code Playgroud)

现在我们可以routerTestProps在测试中使用该功能

const { history, location, match } = routerTestProps('/route/:id', { id: '1' });
Run Code Online (Sandbox Code Playgroud)


Dan*_*noz 10

一位名叫 Timmy Huang 的先生提供了一个解决方案,其中涉及一个简单的模拟......

https://spectrum.chat/react/help/how-do-you-test-components-that-use-routecomponentprops~495fe95b-6925-4e7f-bfe8-65a737c5d24e?m=MTU4Mjk1MjQ4ODQ0MA==

const routeComponentPropsMock = {
  history: {} as any,
  location: {} as any,
  match: {} as any,
}
Run Code Online (Sandbox Code Playgroud)

我用 Jest 试过这个,它奏效了。我的组件有这个签名...

export const MyComponent: React.FC<RouteComponentProps> = ({location}:RouteComponentProps) => {
Run Code Online (Sandbox Code Playgroud)

我确认组件负载的基本测试看起来像这样......

function renderMyComponent() {
  return render(
    <MyComponent {...routeComponentPropsMock}/>
  );
}
Run Code Online (Sandbox Code Playgroud)


Azi*_*ziz 5

我一直在寻找一个很好的解决方案。我希望我可以在 mapStateToProps 函数或类似的东西中做到这一点,但还没有能够做到这一点。

我能做的最好的事情就是对此进行模拟并传递比赛,位置和历史。我使用了以下内容:

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

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;
}
Run Code Online (Sandbox Code Playgroud)

然后在我的测试中我做了:

    var routerProps = getMockRouterProps<ReduxTestComponentProps>(null);

    const wrapper = mount<ReduxTestComponent, ReduxTestComponentState>(
            <ReduxTestComponent
                history={routerProps.history}
                location={routerProps.location}
                match={routerProps.match}
                isLoadingTodo={false}
                todos={todos}
                addAsyncTodoActionDispatch={() => mockTodoAddDispatch()}
                deleteTodoActionDispatch={() => mockTodoDeleteDispatch()}
                />
      );
Run Code Online (Sandbox Code Playgroud)