首页 > 解决方案 > 模拟嵌套在路由器和 Provider 组件中的 this.props.dispatch

问题描述

我正在尝试为我的代码编写一个单元测试,该代码嵌套在路由器的提供程序中。我的组件通过调用 this.props.dispatch(ACTION) 来使用 redux。为了测试这一点,我需要在我的测试中模拟 this.props.dispatch 但我无法做到这一点。

似乎出于某种原因,问题在于 Login 嵌套在 Provider 和 Router 组件中,这导致 Login 忽略了我通过它的任何类型的模拟道具。如果您查看注释掉的代码行,它可以工作 - 唯一的区别是登录组件没有嵌套在此示例中的 Provider 和 Router 中。

所以我的问题是,如果我想模拟这样的嵌套组件的道具,我应该做些什么额外的事情吗?

describe("Pokedex", () => {
    beforeEach(() => {
        var dispatch = jest.fn();
        var props = {
            dispatch
        };
        // wrapper = mount(<Login {...props} />); Correctly mocks dispatch
        wrapper = mount(
            <Provider store={store}>
                <Router >
                    <Login {...props} />
                </Router>
            </Provider>
        );
        wrapper.setState({ loading: false });
        store.clearActions();
    });

登录组件的一部分:

export class Login extends PureComponent {

    constructor(props) {
        super(props);
        console.log("Props", this.props.dispatch);

        this.props.dispatch(userActions.resetError());

        this.state = {
            username: '',
            password: ''
        };

/** Extra code omitted **/

    }

标签: reactjsunit-testingjestjs

解决方案


推荐阅读