使用 Recompose 测试 HOC

Testing HOC with Recompose

我在测试我的 HOC 上是否触发了 prop 时遇到了一些问题。

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);

我想知道当 user 不是用户实例时 fetchCurrentUser 是否被触发。

到目前为止我的测试中有:

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);
});

看来我不能用这种方式更换道具。如果我在生命周期方法中记录 this.props,我永远不会看到 user: 'string'

提前致谢

您需要浅安装组件才能测试其功能。

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);
});

好的,在 shubham-khatri 的帮助下,这就是我所做的让它发挥作用的方法。

将组件分成两个不同的组件,并测试了仅调用的组件。这样我就可以模拟测试中传递的道具。

组件:

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';

const Connected = connect(state => ({
  user: getUser(state),
}),
{ fetchCurrentUser });

export const Enhanced = lifecycle({
  componentDidMount() {
    if (this.props.user instanceof User) return;

    this.props.fetchCurrentUser();
  },
});

export default Component => compose(
  Connected,
  Enhanced,
)(Component);

测试:

describe('Fetching user', () => {
    const setup = (moreProps) => {
      const props = {
        fetchCurrentUser: jest.fn(),
        ...moreProps,
      };

      const EnhancedStub = compose(
        Enhanced,
      )(Component);

      const enzymeWrapper = shallow(
        <EnhancedStub {...props} />,
      );

      return {
        props,
        enzymeWrapper,
      };
    };

    it('fetches user if user is not a User instance', () => {
      expect(setup().props.fetchCurrentUser.mock.calls.length).toEqual(1);
    });

    it('does NOT fetch user if user is a User instance', () => {
      expect(setup({ user: new User({ first_name: 'Walter' }) }).props.fetchCurrentUser.mock.calls.length).toEqual(0);
    });
  });

希望对某人有所帮助。