自定义 Hook
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;
测试代码
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‘);
});