reactjs 如何测试一个redux action是否在useEffect中被调用?

uoifb46i  于 12个月前  发布在  React
关注(0)|答案(1)|浏览(94)

我想测试一下在useEffect内部调用了一个redux操作。
我有我的根组件作为-

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。任何关于我做错了什么的建议都会有很大的帮助。

ee7vknir

ee7vknir1#

jest.spyOn向原始方法添加了一个“mock wrapper”,因此您需要将模块作为对象提供给jest.spyOn,然后在测试期间,组件将使用从提供给spyOn的模块导入的“mock wrapper”方法。

import * as actions from '../actions' // here should be the path to the file where clearState action is located

const mockStore = configureStore([]);

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

    // here { clearState } was replaced with actions
    const clearStateSpy = jest.spyOn(actions, '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();
  });
});

字符串

相关问题