Reactjs 如何测试if语句的内部使用效果?

Reactjs 如何测试if语句的内部使用效果?,reactjs,react-redux,jestjs,enzyme,use-effect,Reactjs,React Redux,Jestjs,Enzyme,Use Effect,我试图测试if语句中的useffect哪个主要依赖项riskSelection,来自useSelector的react redux库。Jest覆盖表明第20-21行缺失 App.tsx function App(): JSX.Element { const riskSelection = useAppSelector(selectRiskSelection); const {save} = useActions({...riskSelectorActions}); const ris

我试图测试
if
语句中的
useffect
哪个主要依赖项
riskSelection
,来自
useSelector
react redux
库。Jest覆盖表明第20-21行缺失

App.tsx

function App(): JSX.Element {
  const riskSelection = useAppSelector(selectRiskSelection);
  const {save} = useActions({...riskSelectorActions});
  const risks: Risk = risks_levels;
  const [data, setData] = useState<Data[]>();

  const width = 450,
    height = 450,
    margin = 40;
  const radius = Math.min(width, height) / 2 - margin;

  useEffect(() => {
    if (typeof riskSelection !== 'undefined') {      // line 20
      setData(Object.values(risks[riskSelection]));  // line 21
    }
  }, [riskSelection, risks]);

  return (
    <div>
        <ul className={style.riskSelectorUl}>
          {new Array(10).fill(0).map((v, i: number) => (
            <li
              className={Number(riskSelection) === i + 1 ? style.selected : ''}
              onClick={() => save({riskSelection: `${i + 1}`})}
              key={i}
            >
              {i + 1}
            </li>
          ))}
        </ul>
      {data && (
        <PieSVG
          data={data}
          width={width}
          height={height}
          innerRadius={100}
          outerRadius={radius}
        />
      )}
    </div>
  );
}

export default App;
jest.mock('../utils/redux/hooks');
import * as reduxHooks from '../utils/redux/hooks';

describe('App', () => {
  let wrapper: any;

  beforeEach(() => {
    jest
      .spyOn(reduxHooks, 'useAppSelector')
      .mockImplementation((f) => f({riskSelector: {riskSelection: undefined}}));
    wrapper = shallow(<Dummy />);
  });

  afterEach(() => {
    jest.clearAllMocks();
  });

  it('shows pie chart', () => {    
    reduxHooks.useAppSelector(() => '1');
    expect(wrapper.find(PieSVG)).toHaveLength(1);
  });
});
我使用
mockImplementation
尝试更改
riskSelector
,但这只是初始化了我的redux状态

当用户单击使用
保存
操作的
  • 时,会触发此redux状态更改

    也许我不应该让我的UI更改如此依赖于
    useffect

    hook.ts

    import {TypedUseSelectorHook, useSelector} from 'react-redux';
    
    import type {RootState} from './store';
    
    export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
    
    从'react redux'导入{typedusselectorhook,useSelector};
    从“./store”导入类型{RootState};
    导出常量useAppSelector:TypeDusseSelectorHook=useSelector;
    
    您没有使用
    保存
    操作。如果是不相关的代码,请删除它。@slideshowp2我刚刚添加了使用它的部分。