【问题标题】:Connected Component testing with certain prop (React/Redux)使用特定道具进行连接组件测试(React/Redux)
【发布时间】:2019-01-20 00:49:02
【问题描述】:

我有一个带有 Redux @connect 装饰器的 react 组件,例如:

import React, { Component } from 'react'
import { connect } from 'react-redux'

@connect(mapStateToProps, 
{
    onPress: () => {...code}) // Component receives this func, not passed from the test
} 
export class Component extends Component {
    render () {
        return <button onclick={this.props.onPress>....</button> 
    }
}

我遇到了一个问题,在测试文件中传递给组件的模拟函数没有传递给组件:

const store = createStore(
    combineReducers({name: reducer})
);
const ComponentConnected = connect(..., {
    onPress: {jest.fn()} // Component doesn't receive this mock
})(() =>(<Component />));

describe('Component testing', () => {
    it('should render component', () => {
        const wrapper = mount(
            <Provider store={store}>
                <ComponentConnected />
            </Provider>
        );
        expect(wrapper.find(Component)).toHaveLength(1);
    });
});

另外,我尝试将模拟函数作为经过测试的组件道具传递,它也没有帮助。不重写组件@connect装饰器是否可以解决这个问题?

【问题讨论】:

    标签: javascript reactjs unit-testing react-redux jestjs


    【解决方案1】:

    我发现了如何将道具传递给连接的组件。我使用了 shallow、dive 和 setProps 酶法:

    describe('Component testing', () => {
        it('should render component', () => {
            const wrapper = shallow(
                <Provider store={store}>
                    <ComponentConnected />
                </Provider>
            );
            const connectedComponentWrapper = wrapper.dive().dive();
            connectedComponentWrapper.setProps({anyProp: 'anyProp'});
            });
        });
    

    【讨论】:

      【解决方案2】:

      我认为,而不是模拟 redux-connect 的连接功能。你应该模拟动作本身。将 ../actions 替换为您的操作文件。

      import { onPress } from "../actions";
      jest.mock("../actions");
      
      onPress.mockReturnValue({ someval: 1 });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-09
        • 2018-03-12
        • 1970-01-01
        • 2021-04-03
        • 1970-01-01
        • 2019-06-02
        • 2017-11-26
        • 1970-01-01
        相关资源
        最近更新 更多