Jest 模拟 useEffect 更改 react 钩子顺序更改

时间:2021-07-12 15:24:52

标签: javascript reactjs unit-testing jestjs mocking

在 Jest 测试中,我只是像下面那样模拟 useEffect。

jest.spyOn(React, "useEffect").mockImplementationOnce(cb => cb()());

describe("Tab sequence 2 when payment type is Direct Payment", () => {
  it("should be able to move tab correctly", async () => {
    act(() => {
      render(
        <Provider store={store}>
          <Home />
        </Provider>
      );
    });

在 Home.tsx 中,我按顺序有以下钩子。

const RegPaymentHome: React.FC<IRegPaymentHome> = (props) => {
    const { t } = useTranslation();
    const [showCaseInfo, setShowCaseInfo] = useState<boolean>(false);
    const [ledgerAccNo, setLedgerAccNo] = useState<string>('');
    const [paymentTypeName, setPaymentTypeName] = useState<string>(
        '47 - Manuell betaling klientkonto'
    );
    const [caseDetails, setCaseDetails] = useState<Array<IRegPaymentForm>>([]);
    const [addedAmount, setAddedAmount] = useState<any>(0);
    const [paymentTypeCode, setPaymentTypeCode] = useState<string>('ORP2M');
    const inputCaseNoRef = React.useRef<any>();
    const paymentSelectRef = React.useRef<any>();
    const inputCaseAmountRef = React.useRef<any>();
    

    useEffect(() => {
        getPaymentTypes('ALL');
    }, []);

但是当我监视 useEffect 时,我在玩笑中遇到了以下错误。我在这里错过了什么?

   Previous render            Next render
   ------------------------------------------------------
1. useContext                 useContext
2. useState                   useState
3. useRef                     useRef
4. useRef                     useEffect

0 个答案:

没有答案