Skip to content

A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.

8.3 KB
Raw Blame
import * as React from "react";
import * as ReactDOM from "react-dom";
import * as TestUtils from "react-dom/test-utils";
import { {{name}} } from "../{{name}}";
import { IInputs } from "../{{name}}/generated/ManifestTypes";
import { mockContext, mockDataSet } from "../test/pcf-context";

type DataSetRecord = ComponentFramework.PropertyHelper.DataSetApi.EntityRecord;

interface DatasetElementProps {
    onNextPage: () => void;
    onPreviousPage: () => void;
    onOpenRecord: (record: DataSetRecord) => void;
}

function render(dataSet?: IInputs["sampleDataSet"] | null) {
    const control = new {{name}}();
    const context = mockContext<IInputs>({});
    if (dataSet !== undefined) Reflect.set(context.parameters, "sampleDataSet", dataSet);
    const container = document.createElement("div");
    control.init();
    TestUtils.act(() => {
        ReactDOM.render(control.updateView(context), container);
    });

    return {
        control,
        container,
        context,
        dataSet,
        update: () => TestUtils.act(() => {
            ReactDOM.render(control.updateView(context), container);
        }),
        element: control.updateView(context) as React.ReactElement<DatasetElementProps>,
        buttons: () => Array.from(container.querySelectorAll("button")) as HTMLButtonElement[],
        pagerButtons: () => Array.from(container.querySelectorAll("button"))
            .filter((button) => button.textContent === "Previous" || button.textContent === "Next") as HTMLButtonElement[],
        headers: () => Array.from(container.querySelectorAll("th")).map((header) => ({
            text: header.textContent,
            scope: header.getAttribute("scope"),
        })),
        rows: () => Array.from(container.querySelectorAll("tbody tr")),
    };
}

function dataSet(options = {}) {
    return mockDataSet({
        first: { sampleProperty: "First" },
        second: { sampleProperty: "Second" },
    }, [{ name: "sampleProperty", displayName: "Value" }], options) as IInputs["sampleDataSet"];
}

test("loading state renders a message", () => {
    const { container, pagerButtons } = render(dataSet({ loading: true, hasNextPage: true, hasPreviousPage: true }));

    expect(container.textContent).toContain("Loading records");
    expect(pagerButtons().map((button) => button.disabled)).toEqual([true, true]);
});

test("empty state renders a message", () => {
    const empty = mockDataSet({}, [{ name: "sampleProperty" }]) as IInputs["sampleDataSet"];
    const { container } = render(empty);

    expect(container.textContent).toContain("No records");
});

test("error state renders the dataset error message", () => {
    const { container } = render(dataSet({ error: true, errorMessage: "Access denied" }));

    expect(container.textContent).toContain("Access denied");
});

test("renders records in sortedRecordIds order", () => {
    const ds = dataSet();
    ds.sortedRecordIds = ["second", "first"];
    const { rows } = render(ds);

    expect(rows().map((row) => row.textContent)).toEqual(["SecondOpen", "FirstOpen"]);
});

test("renders column headers", () => {
    const { headers } = render(dataSet());

    expect(headers()).toEqual([
        { text: "Value", scope: "col" },
        { text: "Actions", scope: "col" },
    ]);
});

test("next and previous paging stay locked until the framework completes loading", async () => {
    const ds = dataSet({ hasNextPage: true, hasPreviousPage: true });
    const { control, container, element } = render(ds);

    element.props.onNextPage();
    await Promise.resolve();

    element.props.onPreviousPage();
    element.props.onNextPage();

    expect(ds.paging.loadNextPage).toHaveBeenCalledTimes(1);
    expect(ds.paging.loadNextPage).toHaveReturnedWith(undefined);
    expect(ds.paging.loadPreviousPage).not.toHaveBeenCalled();

    ds.loading = true;
    ReactDOM.render(control.updateView(mockContext<IInputs>({ sampleDataSet: ds })), container);
    const pagerButtons = () => Array.from(container.querySelectorAll("button"))
        .filter((button) => button.textContent === "Previous" || button.textContent === "Next") as HTMLButtonElement[];
    expect(pagerButtons().map((button) => button.disabled)).toEqual([true, true]);

    ds.loading = false;
    ReactDOM.render(control.updateView(mockContext<IInputs>({ sampleDataSet: ds })), container);

    expect(pagerButtons().map((button) => button.disabled)).toEqual([false, false]);
});

test("paging buttons disable immediately before any host update", () => {
    const ds = dataSet({ hasNextPage: true, hasPreviousPage: true });
    const { pagerButtons } = render(ds);
    const next = pagerButtons().find((button) => button.textContent === "Next") as HTMLButtonElement;

    TestUtils.act(() => TestUtils.Simulate.click(next));

    expect(ds.paging.loadNextPage).toHaveReturnedWith(undefined);
    expect(pagerButtons().map((button) => button.disabled)).toEqual([true, true]);
});

test.each(["Next", "Previous"])("completion-only update releases a %s paging request and local busy state", (label) => {
    const ds = dataSet({ hasNextPage: true, hasPreviousPage: true });
    const { pagerButtons, element, update, rows } = render(ds);
    const button = pagerButtons().find((item) => item.textContent === label) as HTMLButtonElement;
    const loadPage = label === "Next" ? ds.paging.loadNextPage : ds.paging.loadPreviousPage;

    TestUtils.act(() => TestUtils.Simulate.click(button));
    element.props.onNextPage();
    element.props.onPreviousPage();
    expect(loadPage).toHaveBeenCalledTimes(1);
    expect(loadPage).toHaveReturnedWith(undefined);

    ds.sortedRecordIds = ["second", "first"];
    update();

    expect(rows().map((row) => row.textContent)).toEqual(["SecondOpen", "FirstOpen"]);
    expect(pagerButtons().map((item) => item.disabled)).toEqual([false, false]);
    TestUtils.act(() => TestUtils.Simulate.click(button));
    expect(loadPage).toHaveBeenCalledTimes(2);
});

test.each([undefined, null])("missing dataset %p renders safely and releases pending paging", (missing) => {
    expect(render(missing).container.textContent).toContain("No dataset parameter was provided");

    const ds = dataSet({ hasNextPage: true, hasPreviousPage: true });
    const { pagerButtons, update, context, container } = render(ds);
    const next = pagerButtons().find((button) => button.textContent === "Next") as HTMLButtonElement;
    TestUtils.act(() => TestUtils.Simulate.click(next));

    Reflect.set(context.parameters, "sampleDataSet", missing);
    expect(update).not.toThrow();
    expect(container.textContent).toContain("No dataset parameter was provided");

    context.parameters.sampleDataSet = ds;
    update();
    expect(pagerButtons().map((button) => button.disabled)).toEqual([false, false]);
});

test("dataset errors release pending paging without requiring a loading update", () => {
    const ds = dataSet({ hasNextPage: true, hasPreviousPage: true });
    const { pagerButtons, update, container } = render(ds);
    const next = pagerButtons().find((button) => button.textContent === "Next") as HTMLButtonElement;
    TestUtils.act(() => TestUtils.Simulate.click(next));

    ds.error = true;
    ds.errorMessage = "Access denied";
    update();
    expect(container.textContent).toContain("Access denied");
    expect(pagerButtons().map((button) => button.disabled)).toEqual([false, false]);

    TestUtils.act(() => TestUtils.Simulate.click(next));
    expect(ds.paging.loadNextPage).toHaveBeenCalledTimes(2);
});

test("updateView does not refresh the dataset", () => {
    const ds = dataSet();
    const { control } = render(ds);

    control.updateView(mockContext<IInputs>({ sampleDataSet: ds }));

    expect(ds.refresh).not.toHaveBeenCalled();
});

test("opens records through openDatasetItem", () => {
    const ds = dataSet();
    const { buttons, element } = render(ds);

    expect(buttons()[0].getAttribute("aria-label")).toBe("Open First");

    element.props.onOpenRecord(ds.records.first);

    expect(ds.openDatasetItem).toHaveBeenCalledWith(expect.objectContaining({ id: "first" }));
});

test("open and paging actions render as Fluent v9 buttons", () => {
    const { buttons } = render(dataSet({ hasNextPage: true, hasPreviousPage: true }));

    // fui-Button is the stable class Fluent v9 puts on every Button root.
    expect(buttons().length).toBe(4);
    expect(buttons().every((button) => button.classList.contains("fui-Button"))).toBe(true);
});