I am attempting to test that I am calling one of my mapDispatchToProps functions with args, however I can't seem to get it to work...
I attempted to follow this previous question, but it didn't seem to work for me.
Component.jsx
const mapDispatchToProps = dispatch => ({
myFunction: (data) => dispatch(myAction(data))
});
const Component = ({buttonText, myFunction}) => (
<button data-testid="test" onClick={() => myFunction(123)}>{buttonText}</button>
)
export default connect(null, mapDispatchToProps)(Component);
Actions.js
export const myAction = agentData => ({
type: `MY_ACTION`,
agentData
});
Test.js
import createMockStore from "redux-mock-store";
it('Should pass', () => {
const mockStore = createMockStore();
const store = mockStore({});
const mockUpdate = jest.fn(data => console.log('HIT FUNCTION with ' + data));
const props = {buttonText: 'Click me', myFunction: mockUpdate};
render(
<Provider store={store}>
<Component {...props}/>
</Provider>
);
userEvent.click(screen.queryByTestId('test'));
expect(mockUpdate).toHaveBeenCalled();
expect(mockUpdate).toHaveBeenCalledWith(123);
});
I have also tried moving the myFunction: mockUpdate from the props object into the mockStore({}) initial object, but still no luck...
Your mock
myFunctiondidn't invoke when you click the button. Because the returned value ofmapDispatchToPropswill become the props of the component.You can get the mock
myFunctionvia the second parameter ofmapDispatchToPropsfunction namedownProps. You may want to call the mockmyFunctionwhen dispatching the action. If so,expect(mockUpdate).toHaveBeenCalled();assertion will work.component.tsx:Test result: