如何测试调用传递给 addEventListener 的函数?

问题描述 投票:0回答:0

我有一个 React promt 钩子,用于在未保存内容时通知用户。 为该钩子编写测试时遇到问题。

这是钩子本身:

从“反应”中导入 React,{useEffect};

const PROMPT_MESSAGE =
  "Are you sure you want to leave this page? \nYour unsaved changes will be lost.";

type Props = {
  when: boolean;
};

export const SettingsSavePrompt = ({ when }: Props): JSX.Element => {
  useEffect(() => {
    if (!when) {
      return;
    }

    const handleWindowOrTabClose = (event: BeforeUnloadEvent) => {
      if (event) {
        event.preventDefault();
        // eslint-disable-next-line no-param-reassign
        event.returnValue = PROMPT_MESSAGE;
      }

      return PROMPT_MESSAGE;
    };

    window.addEventListener("beforeunload", handleWindowOrTabClose);

    return () => {
      window.removeEventListener("beforeunload", handleWindowOrTabClose);
    };
  }, [when]);

  return <div />;
};

这是我失败的测试:

it.only("should return the prompt message when beforeunload event is triggered", () => {
    const { unmount } = render(<SettingsSavePrompt when />);

    window.addEventListener("beforeunload", () => {
      jest.fn().mockReturnValue(PROMPT_MESSAGE);
    });

    const event = new Event("beforeunload");
    window.dispatchEvent(event);
    unmount();

    expect(event.returnValue).toEqual(PROMPT_MESSAGE);
  });

我将控制台日志放在

handleWindowOrTabClose
中,但它没有显示任何内容。肯定不会调用简单的函数。

javascript reactjs addeventlistener
© www.soinside.com 2019 - 2024. All rights reserved.