Search code examples
reactjstestinghigher-order-componentsrecompose

Testing HOC with Recompose


I'm having some troubles testing that a prop is fired on my HOC.

import { connect } from 'react-redux';
import { compose, lifecycle } from 'recompose';

import { fetchCurrentUser } from '../../actions/users';
import { getUser } from '../../reducers/users';
import User from '../../models/User';

export default Component => compose(
  connect(state => ({
    user: getUser(state),
  }),
  { fetchCurrentUser }),
  lifecycle({
    componentDidMount() {
      if (this.props.user instanceof User) return;
      this.props.fetchCurrentUser();
    },
  }),
)(Component);

What I'd like to know is whether or not fetchCurrentUser is trigger when user is NOT a User instance.

So far I have that in my test:

it.only('fetches user if user is not a User instance', () => {
  const setup = () => {
  const props = {
    user: 'string',
    fetchCurrentUser: jest.fn(),
   };
   const enzymeWrapper = mounting(props);

   return {
     props,
      enzymeWrapper,
    };
  };

  // That returns 0 so false         
  expect(setup().props.fetchCurrentUser.mock.calls.length).toEqual(1);
});

It seems like I can't replace the props doing it this way. If I log this.props in the lifecycle method, I never see user: 'string'

Thanks in advance


Solution

  • You would need to shallow mount the component in order to test its functionality.

    it.only('fetches user if user is not a User instance', () => {
      const setup = () => {
      const props = {
        user: 'string',
        fetchCurrentUser: jest.fn(),
       };
       // shallow render the component
       const enzymeWrapper = shallow(<Component {...props} />)
    
       return {
          props,
          enzymeWrapper,
        };
      };
    
      expect(setup().props.fetchCurrentUser.mock.calls.length).toEqual(1);
    });