【问题标题】:Test react forceUpdate custom hook useEffect/useState测试 react forceUpdate 自定义钩子 useEffect/useState
【发布时间】:2020-02-19 04:07:42
【问题描述】:

我创建了一个自定义挂钩来强制更新组件,但我在弄清楚如何使用 jest 编写单元测试时遇到问题。

这是钩子


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

export default useForceUpdate;

【问题讨论】:

  • 没有更多上下文很难说。当您说“测试”时,您是指使用 jest 之类的库进行单元测试吗?或者你只是想检查它是否有效?您想通过强制更新解决什么问题?
  • 对不起,我的意思是开玩笑的单元测试。

标签: reactjs jestjs enzyme react-hooks


【解决方案1】:

我可以通过这种方式成功测试这个钩子

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");
    });
  });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-22
    • 2021-12-26
    • 2020-06-03
    • 2020-01-26
    • 2020-12-05
    • 2021-09-10
    • 1970-01-01
    • 2021-04-25
    相关资源
    最近更新 更多