3
votes

I have such component. It is a wrapper component for another component. There is onClick function, which should call the log if is mouse event

import log from './log';

export function withPressedLog(
    Component,
    options,
) {
    class WithPressedLogComponent extends React.Component {
        constructor(props) {
            super(props);
            this.onClick = this.onClick.bind(this);
        }

        public render() {
            const { ...props } = this.props;
            return <Component {...props} onClick={this.onClick} />;
        }

        private onClick(e) {
            if (this.props.onClick !== undefined) {
                this.props.onClick(e);
            }

            if (e) {
                this.props.log();
            }
        }
    }

    const mapDispatchToProps = {
        log: () => log(options),
    };

    return connect(
        undefined,
        mapDispatchToProps,
    )(WithPressedLogComponent);
}

I need to test is it called this.props.log. I have a unit test, but it not works. How I can do it using jest, enzyme?

it("should not log if has not mouse event", () => {
    const onClickMock = jest.fn();
    const logMock = jest.fn();
    const ButtonWithLog = withPressedLog(Button, {
        type: "BUTTON_PRESSED",
    });

    const subject = mountProvider(ButtonWithLog, { onClick: onClickMock, log: logMock });

    const mockedEvent = { target:{} };
    subject.find(ButtonWithLog).simulate("click", mockedEvent);

    expect(onClickMock.mock.calls).toHaveLength(1);
    expect(logMock.mock.calls).toHaveLength(0); // not works correctly, always return []

});

store

const store = createStore(() => ({}));
const dispatchMock = jest.fn();
store.dispatch = dispatchMock;

mountProvider function

function mountProvider(
    Component,
    props,
) {
    return mount(
        <Provider store={store}>
            <Component {...props} />
        </Provider>,
    );
}
1
Where is your mountPovider coming from?Hinrich
Hinrich I add this function into codeQwerty

1 Answers

0
votes

I think the problem here is that you are actually testing the connected component, not the unwrapped component.

Try to isolate the components you are testing more. For example, you can use enzyme's shallow wrapper and the dive method on the connected component, to directly get to the unwrapped component.

Specifically, your problem could be that your connected component is getting the log prop from the store (through mapDispatchToProps), but the store is mocked, so it does not work. In your test, you pass some mock function as prop to the component, but the reference gets lost once the components connects.

helpful thread on github