如何在useEffect中测试if语句?

时间:2021-05-06 23:04:50

标签: reactjs react-redux jestjs enzyme use-effect

我正在尝试测试 if 中的 useEffect 语句,该语句的主要依赖项 riskSelection 来自 useSelector 库中的 react-redux。开玩笑的报道表明第 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;

我的测试应该验证 PieSVG 是否已呈现。为此,我必须模拟 riskSelection 的变化。这就是我需要帮助的地方。

App.test.tsx

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 状态。

用户在点击使用 <li /> 操作的 save 时触发此 redux 状态更改。

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

hook.ts

import {TypedUseSelectorHook, useSelector} from 'react-redux';

import type {RootState} from './store';

export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;

0 个答案:

没有答案