I have the following component.
Looking to test that the router method push within useEffect is being called with a certain path and search.
import React from 'react';
import { compose } from 'redux';
import { withRouter } from 'react-router';
const MyComponent = ({
router: { push, location },
}) => {
const version = 'v2';
React.useEffect(() => {
push({
pathname: `/${version}/new_path`,
search: location.search ? location.search: '',
});
}, []);
return <div>Sample div text</div>
};
const higherOrder = compose(
withRouter,
aCustomHigherOrderC,
);
export default higherOrder(MyComponent);
This is the test I have written to test that the router is being called correctly.
import React from 'react';
import { shallow } from 'enzyme';
import MyComponent from '../src/components/MyComponent';
jest.spyOn(React, 'useEffect').mockImplementation(f => f());
const props = {
router: {
push: jest.fn(),
location: {
search: '?param=1',
},
},
};
describe('MyComponent component tests', () => {
it('should work', () => {
const render = () => shallow(
<MyComponent {...props} />
);
expect(props.router.push).toHaveBeenCalledWith('/v2/new_path?param=1');
});
});
But I get the following error when I run the test.
Error: expect(jest.fn()).toHaveBeenCalledWith(expected)
Expected mock function to have been called with: ["/v2/new_path?param=1"] But it was not called.
It seems like I did not even enter useEffect. Did try to add a break point in there and I do not hit
that break point. Could I please get some advice on what I am doing wrong and how I could test the router
that it is being called with correct path and search param? Thanks.