使用重组测试HOC

时间:2018-09-24 10:00:06

标签: reactjs testing higher-order-components recompose

我在测试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);

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

到目前为止,我已经对此进行了测试:

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'

预先感谢

2 个答案:

答案 0 :(得分:1)

您需要将组件浅装,以测试其功能。

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

答案 1 :(得分:0)

好的,在shubham-khatri的帮助下,这就是我所做的使之工作的方法。

将组件分为2个不同的组件,并仅通过调用对其进行测试。这样我就可以从测试中模拟通过的道具。

组件:

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

希望能帮助某人。