ダミー カウンター コンポーネントの次の簡単なテストがあります。
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");
});
});
私はいくつかの調査を行いましたが、そのようなアプローチに関する適切なリソースを見つけることができませんでした。