0

I have a react component with Redux @connect decorator, for instance:

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?

2 Answers 2

2

I found out how to pass a prop to a connected Component. I used shallow, dive and setProps enzyme methods:

describe('Component testing', () => {
    it('should render component', () => {
        const wrapper = shallow(
            <Provider store={store}>
                <ComponentConnected />
            </Provider>
        );
        const connectedComponentWrapper = wrapper.dive().dive();
        connectedComponentWrapper.setProps({anyProp: 'anyProp'});
        });
    });
Sign up to request clarification or add additional context in comments.

Comments

1

I think, instead of mocking connect function of redux-connect. You should mock the action itself. replace ../actions with your actions file.

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

onPress.mockReturnValue({ someval: 1 });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.