我如何才能开玩笑地测试HOC?

问题描述 投票:0回答:1

我写了一份HOC,目的是为了在我的项目中以动态方式注入减速器,效果很好。但是我很难开玩笑地对此进行测试。我的疑问是如何在withReducer函数内部测试该扩展类返回哪个,以及如何测试是否使用正确的参数调用contextType函数(store.injectReducer)。

我的withReducer.js

/* eslint-disable react/no-deprecated */
import React from 'react';
import { ReactReduxContext } from 'react-redux';

export const withReducer = (key, reducer) => (WrappedComponent) => {
  class Extended extends React.Component {
    static WrappedComponent = WrappedComponent;

    componentWillMount() {
      const { store } = this.context;

      store.injectReducer(key, reducer);
    }

    render() {
      return <WrappedComponent {...this.props} />;
    }
  }

  Extended.contextType = ReactReduxContext;

  return Extended;
};

export default withReducer;

我的测试功能

import React from 'react';
import { shallow } from 'enzyme';
import { identity } from 'lodash';
import { Provider } from 'react-redux';
import { withReducer } from '../withReducer';
import initializeStore from '../initializeStore';

const Component = jest.fn();

let store;
let ComponentWithReducer;
const reducer = identity;

beforeEach(() => {
  store = initializeStore();
  ComponentWithReducer = withReducer('test', reducer)(Component);
});

describe('withReducer', () => {
  it('should propagate props', () => {
    const props = { testProp: 'test' };
    const renderedComponent = shallow(
      <Provider store={store}>
        <ComponentWithReducer {...props} />
      </Provider>, {
        context: { store },
      },
    );

    expect(renderedComponent.dive().props()).toEqual(props); // works
    // how test render() return here
    // how to test that store.injectReducer(key, reducer) was called here
  });
});
reactjs jestjs enzyme
1个回答
0
投票

您可以在商店中模拟injectReducer函数:

const props = { testProp: 'test' };

const mockFn = jest.fn();

const renderedComponent = shallow(
  <Provider store={{ injectReducer: mockFn }}>
    <ComponentWithReducer {...props} />
  </Provider>, {
    context: { store },
  },
);

expect(mockFn).toHaveBeenCalled();
expect(mockFn).toHaveBeenCalledWith('test', reducer);
© www.soinside.com 2019 - 2024. All rights reserved.