如何测试在 useEffect 中调用了 redux 动作?

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

我想测试在 useEffect 中调用了一个 redux 动作。

我的 Root 组件是 -

export default ({ children, initialState = {} }) => {
  return (
    <Provider store={createStore(reducers, initialState, applyMiddleware(thunk))}>
      {children}
    </Provider>
  );
};

包裹在组件内部的组件-

import { clearState } from '../actions';
const App= (props) => {
  useEffect(() => {
    props.clearState();
  }, []);
  return (
    <div>
      App 
    </div>
  );
};

/**
 * Map the state to properties so that the component only
 * get relevant data.
 *
 * @param {object} state The current application state
 * @return {object} Data from the state that the component needs
 */
const mapStateToProps = () => {
  return {};
};

export default connect(mapStateToProps, {
  clearState
})(App);

我的 clearState 动作是 -

export const clearState = () => {
  return async (dispatch) => {
    dispatch({ type: CLEAR_STATE, payload: {} });
  };
};

我正在尝试测试当 App 组件加载时调用 clearState 操作。

const mockStore = configureStore([]);

describe('App component', () => {
  it('should call clearState action on component mount', () => {
    // Create a mock store
    const store = mockStore({});

    // Create a spy for the clearState action
    const clearStateSpy = jest.spyOn({ clearState }, 'clearState');

    // Mount the component with the Provider and store
    const wrapper = mount(
      <Root store={store}>
        <App/>
      </Root>
    );

    // Expect the clearState action to have been called
    expect(clearStateSpy).toHaveBeenCalled();
  });
});

但是测试失败了,因为调用次数返回为 0。任何关于我做错了什么的建议都会有很大帮助。

reactjs redux react-hooks jestjs enzyme
© www.soinside.com 2019 - 2024. All rights reserved.