测试反应力更新自定义钩子useEffect / useState

时间:2019-10-23 00:26:27

标签: reactjs jestjs enzyme react-hooks

我创建了一个自定义挂钩来强制组件进行更新,但是在弄清楚如何编写带有笑话的单元测试时遇到了问题。

这是钩子


function useForceUpdate(condition) {
  const [, setState] = useState(0);
  const forceUpdate = () => setState(1);
  useEffect(() => {
    if (condition) {
      forceUpdate();
    }
  }, [condition]);
}

export default useForceUpdate;

1 个答案:

答案 0 :(得分:0)

我能够通过这种方式成功测试此钩子

import React from "react";
import useForceUpdate from "hooks/use-force-update";

const Component = ({ shouldUpdate }) => {
  const hasUpdated = useForceUpdate(shouldUpdate);
  return <div>{hasUpdated}</div>;
};

describe("useForceUpdate", () => {
  let subject;
  let props;

  beforeEach(() => {
    props = { shouldUpdate: true };
    subject = memoize(() => mount(<Component {...props} />));
  });

  describe("when the condition is true", () => {
    it("it calls forceUpdate", () => {
      expect(
        subject()
          .find("div")
          .text()
      ).toBe("1");
    });
  });

  describe("when the condition is false", () => {
    beforeEach(() => {
      props = { shouldUpdate: false };
    });
    it("it does not call forceUpdate", () => {
      expect(
        subject()
          .find("div")
          .text()
      ).toBe("0");
    });
  });
});