简体   繁体   English

使用某些道具(React / Redux)进行连接组件测试

[英]Connected Component testing with certain prop (React/Redux)

I have a react component with Redux @connect decorator, for instance: 我有一个带有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> 
    }
}

I faced with a problem that mocked functions passed to the component in a test file are not passed into the component: 我面临一个问题,即在测试文件中传递给组件的模拟函数未传递给组件:

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);
    });
});

Also, I tried to pass the mock function as a tested component prop, it didn't help too. 另外,我尝试将模拟功能作为经过测试的组件道具传递,但也没有帮助。 Is it possible to solve this problem without re-writing component @connect decorator? 是否可以在不重写组件@connect装饰器的情况下解决此问题?

I think, instead of mocking connect function of redux-connect. 我认为,不是嘲笑redux-connect的连接功能。 You should mock the action itself. 您应该模拟动作本身。 replace ../actions with your actions file. 用您的动作文件替换../actions

import { onPress } from "../actions";
jest.mock("../actions");

onPress.mockReturnValue({ someval: 1 });

I found out how to pass a prop to a connected Component. 我发现了如何将道具传递给连接的组件。 I used shallow, dive and setProps enzyme methods: 我使用了浅水,潜水和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'});
        });
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM