0

我对虚拟计数器组件进行了以下简单测试:

describe("Counter", () => {
  it("initially displays 0", () => {
    render(<Counter />);
    expect(screen.getByText("Counter value is 0")).toBeInTheDocument();
  });

  it("displays the given initial value", () => {
    render(<Counter initialValue={10} />);
    expect(screen.getByText("Counter value is 10")).toBeInTheDocument();
  });

  it("has a button for incrementing the value", () => {
    render(<Counter />);
    userEvent.click(screen.getByRole("button", { name: "+1" }));
    expect(screen.getByText("Counter value is 1")).toBeInTheDocument();
  });

  describe("when the maxValue is given", () => {
    it("does not allow to increment the value above the given maximum", () => {
      render(<Counter initialValue={9} maxValue={10} />);
      userEvent.click(screen.getByRole("button", { name: "+1" }));
      expect(screen.getByText("Counter value is 10")).toBeInTheDocument();
      expect(screen.getByRole("button", { name: "+1" })).toBeDisabled();
    });
  });

  it("has a button for decrementing the value", () => {
    render(<Counter initialValue={2} />);
    userEvent.click(screen.getByRole("button", { name: "-1" }));
    expect(screen.getByText("Counter value is 1")).toBeInTheDocument();
  });

  it("does not allow to decrement the value below zero", () => {
    render(<Counter initialValue={0} />);
    expect(screen.getByRole("button", { name: "-1" })).toBeDisabled();

    userEvent.click(screen.getByRole("button", { name: "-1" }));
    expect(screen.getByText("Counter value is 0")).toBeInTheDocument();
  });

  it("has a button for resetting the value", () => {
    render(<Counter initialValue={2} />);
    userEvent.click(screen.getByRole("button", { name: "reset" }));
    expect(screen.getByText("Counter value is 0")).toBeInTheDocument();
  });
});

用一些方便的助手来干掉它是一个好习惯吗,比如:

describe("<Counter /> component", () => {
  const getIncrementButton = () => screen.getByRole("button", { name: "+1" });

  const getDecrementButton = () => screen.getByRole("button", { name: "-1" });

  it("has a button for incrementing the value", () => {
    render(<Counter />);
    userEvent.click(getIncrementButton());
    expect(getValue()).toHaveTextContent("Counter value is 1");
  });

});

我做了一些研究,但找不到任何关于这种方法的体面资源。

4

0 回答 0