DEV Community

Dennis Zhang
Dennis Zhang

Posted on

测试自定义 Hook

自定义 Hook

useInput.js
import { useSelector, useDispatch } from 'react-redux';

function useInput() {
  const value = useSelector(state => state.value);
  const dispatch = useDispatch();

  const setValue = (newValue) => {
    dispatch({ type: 'SET_VALUE', payload: newValue });
  };

  return { value, setValue };
}

export default useInput;
Enter fullscreen mode Exit fullscreen mode

测试代码

// useInput.test.js
import { renderHook, act } from '@testing-library/react-hooks';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import inputReducer from './store'; // Assume this exports the reducer
import useInput from './useInput';

// Helper function to render hook with Redux
const renderHookWithRedux = (hook, { initialState, store = createStore(inputReducer, initialState) } = {}) => {
  const wrapper = ({ children }) => <Provider store={store}>{children}</Provider>;
  return renderHook(hook, { wrapper });
};

test('should update value after rerender with new initial state', () => {
  const { result, rerender } = renderHookWithRedux(
    ({ initialValue }) => useInput(initialValue), 
    { initialState: { value: 'initial' } }
  );

  expect(result.current.value).toBe('initial');

  // Create a new store with a different initial state
  const newStore = createStore(inputReducer, { value: 'updated' });

  // Rerender with the new store
  rerender({ initialState: { value: 'updated' }, store: newStore });

  expect(result.current.value).toBe('updated');
});

Enter fullscreen mode Exit fullscreen mode

Top comments (0)