Skip to content

Commit

Permalink
Try testing differently
Browse files Browse the repository at this point in the history
  • Loading branch information
TrangPham committed Mar 11, 2024
1 parent 1a836ed commit 822e555
Showing 1 changed file with 34 additions and 26 deletions.
60 changes: 34 additions & 26 deletions src/controls/BooleanControl.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,49 +4,57 @@ import { userEvent } from "@testing-library/user-event";
import { render } from "../common/test-render";

test("renders the Checkbox component", async () => {
render(
{
schema: {
type: "object",
properties: { adult: { type: "boolean", title: "Adult"} },
},
}
);
render({
schema: {
type: "object",
properties: { adult: { type: "boolean", title: "Adult" } },
},
});

const checkbox = await screen.findByLabelText("Adult");
expect(checkbox).toBeInTheDocument();
expect(checkbox).not.toBeChecked();
expect(checkbox).toBeEnabled();
// check that there is an checkbox
expect(checkbox.tagName).toBe("INPUT");
expect(checkbox.getAttribute("type")).toBe("checkbox");
const checkbox = await screen.findByLabelText("Adult");
expect(checkbox).toBeInTheDocument();
expect(checkbox).not.toBeChecked();
expect(checkbox).toBeEnabled();
// check that there is an checkbox
expect(checkbox.tagName).toBe("INPUT");
expect(checkbox.getAttribute("type")).toBe("checkbox");
});


test("handles onChange event correctly", async () => {
const updateData = vi.fn()
const updateData = vi.fn();
render({
schema: {
type: "object",
properties: { name: { type: "boolean", title: "Name" } },
},
data: { name: false},
onChange: (result) => {console.log(result); updateData(result)},
data: { name: false },
onChange: (result) => {
console.log(result);
updateData(result);
},
});

const checkbox = await screen.findByLabelText("Name");
expect(checkbox).not.toBeChecked();
expect(updateData).not.toHaveBeenCalled();
// Called with the default when initialized
expect(updateData).toHaveBeenLastCalledWith({
data: { name: false },
errors: [],
});

await userEvent.click(checkbox);
expect(checkbox).toBeChecked();
// FYI the calls to updateData lag behind the actual checkbox state. Not sure why.
// It could be the difference between json-forms handleChange(path, value) and the onChange event.
expect(updateData).toHaveBeenLastCalledWith({ data: {name: false }, errors: []});
expect(updateData).toHaveBeenLastCalledWith({
data: { name: true },
errors: [],
});

await userEvent.click(checkbox);
expect(checkbox).not.toBeChecked();
expect(updateData).toHaveBeenLastCalledWith({ data: {name: true }, errors: []});
expect(updateData).toHaveBeenLastCalledWith({
data: { name: false },
errors: [],
});

expect(updateData).toBeCalledTimes(2);
});
expect(updateData).toBeCalledTimes(3);
});

0 comments on commit 822e555

Please sign in to comment.