使用 enzyme、mocha 和 chai 测试带有回调的 window 事件 addEventListener

Testing a window event addEventListener with a callback using enzyme, mocha and chai

我在测试我的 window addEventListener 中的回调时遇到问题,该回调包含在 useEffect 中。我无法获得回调 setHighRes

的报道
...  
return () => {
          window.removeEventListener("ATF_DONE", setHighRes);
        };

JSX 文件

  // Checks to see if image is cached
  const isCached = src => {
    const img = new Image(); // eslint-disable-line
    img.src = src;
    const complete = img.complete;
    img.src = "";
    return complete;
  };

  const [isHighRes, lazySetIsHighRes] = useState(
    !isCached(`${images[0].normal}?wid=200&hei=200`)
  );

  useEffect(() => {
    // If image is cached load the high res image after the ATF_DONE event
    if (!isHighRes) {
      const setHighRes = () => {
        lazySetIsHighRes(true);
        window.removeEventListener("ATF_DONE", setHighRes);
      };
      window.setTimeout(() => {
        window.addEventListener("ATF_DONE", setHighRes);
        return () => {
          window.removeEventListener("ATF_DONE", setHighRes);
        };
      }, ATF_TIMEOUT)
    }
    return null;
  }, []);

我尝试在 spec.jsx 中执行此操作,但它失败了,因为预期 addEventListener 已使用参数调用

    beforeEach(() => {
      sandbox = sinon.sandbox.create();
      sinon.stub(window, "addEventListener");
      sinon.stub(window, "removeEventListener");
      sandbox.stub(window, "Image").callsFake(() => {
        const image = new Image.wrappedMethod();
        sandbox.stub(image, "complete").value(complete);
        return image;
      });


    it.only("should load low res image if image is cached", () => {
      const clock = sinon.useFakeTimers();
      clock.tick(8000);
        expect(window.addEventListener).to.have.been.calledWith("ATF_DONE", "setHighRes");
    })

看来您可以手动分派事件来触发对我有用的回调

window.dispatchEvent(new Event("ATF_DONE"));