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.

16.9 KB
Raw Blame
import { {{name}} } from "../{{name}}";
import { IInputs } from "../{{name}}/generated/ManifestTypes";
import { mockContext, mockWebApi } from "../test/pcf-context";

type LookupParameter = ComponentFramework.PropertyTypes.LookupProperty;

const accountMetadata = {
    primaryIdAttribute: "accountid",
    primaryNameAttribute: "accountname",
    metadata: {},
};

function lookupProperty(
    raw: ComponentFramework.LookupValue[] = [],
    options: { readable?: boolean; editable?: boolean } = {},
): LookupParameter {
    return {
        raw,
        formatted: raw[0]?.name ?? "",
        type: "Lookup.Simple",
        security: {
            readable: options.readable ?? true,
            editable: options.editable ?? true,
            secured: options.readable === false || options.editable === false,
        },
    } as unknown as LookupParameter;
}

function createResponse(entities: ComponentFramework.WebApi.Entity[], nextLink?: string) {
    return { entities, nextLink } as ComponentFramework.WebApi.RetrieveMultipleResponse;
}

function deferredResponse() {
    let resolve!: (value: ComponentFramework.WebApi.RetrieveMultipleResponse) => void;
    const promise = new Promise<ComponentFramework.WebApi.RetrieveMultipleResponse>((done) => {
        resolve = done;
    });
    return { promise, resolve };
}

async function flushPromises() {
    await Promise.resolve();
    await Promise.resolve();
    await new Promise((resolve) => setTimeout(resolve, 0));
    await Promise.resolve();
}

function mount(
    parameter: LookupParameter | undefined,
    options: {
        disabled?: boolean;
        webAPI?: ComponentFramework.WebApi;
        metadata?: Record<string, unknown>;
        getEntityMetadata?: ComponentFramework.Utility["getEntityMetadata"];
    } = {},
) {
    const control = new {{name}}();
    const notify = jest.fn();
    const container = document.createElement("div");
    const context = mockContext<IInputs>(
        {
            ...(parameter ? { lookupValue: parameter as IInputs["lookupValue"] } : {}),
            targetTable: {
                raw: "account",
                formatted: "account",
                security: { readable: true, editable: true, secured: false },
            } as IInputs["targetTable"],
            selectableFilter: {
                raw: "statecode eq 0",
                formatted: "statecode eq 0",
                security: { readable: true, editable: true, secured: false },
            } as IInputs["selectableFilter"],
        },
        {
            disabled: options.disabled,
            webAPI: options.webAPI ?? mockWebApi({
                retrieveMultipleRecords: jest.fn(async (_entityLogicalName: string, _query?: string, _maxPageSize?: number) => createResponse([
                    { accountid: "11111111-1111-4111-8111-111111111111", accountname: "Active account" },
                ])),
            }),
            utils: {
                getEntityMetadata: options.getEntityMetadata ?? jest.fn(async () => options.metadata ?? accountMetadata),
            },
        },
    );

    control.init(context, notify, {}, container);

    return {
        control,
        notify,
        container,
        context,
        select: () => container.querySelector("select") as HTMLSelectElement,
        status: () => container.querySelector("[role='status']") as HTMLDivElement,
    };
}

test("loads selectable lookup rows through Learn-shaped metadata and writes a LookupValue output", async () => {
    const retrieveMultipleRecords = jest.fn()
        .mockResolvedValueOnce(createResponse([
            { accountid: "11111111-1111-4111-8111-111111111111", accountname: "Alpha" },
        ], "https://contoso.crm.dynamics.com/api/data/v9.2/accounts?$skiptoken=page2"))
        .mockResolvedValueOnce(createResponse([
            { accountid: "22222222-2222-4222-8222-222222222222", accountname: "Beta" },
        ]));
    const mounted = mount(lookupProperty(), {
        webAPI: mockWebApi({ retrieveMultipleRecords }),
    });

    await flushPromises();
    mounted.select().value = "22222222-2222-4222-8222-222222222222";
    mounted.select().dispatchEvent(new Event("change"));

    expect(retrieveMultipleRecords).toHaveBeenNthCalledWith(
        1,
        "account",
        "?$select=accountid,accountname&$filter=statecode%20eq%200&$orderby=accountname%20asc",
        25,
    );
    expect(retrieveMultipleRecords).toHaveBeenNthCalledWith(
        2,
        "account",
        "?$skiptoken=page2",
        25,
    );
    expect(mounted.notify).toHaveBeenCalledTimes(1);
    expect(mounted.control.getOutputs()).toEqual({
        lookupValue: [{ id: "22222222-2222-4222-8222-222222222222", name: "Beta", entityType: "account" }],
    });
});

test("target table comes from configuration, not the lookup property object", async () => {
    const retrieveMultipleRecords = jest.fn(async (_entityLogicalName: string, _query?: string, _maxPageSize?: number) => createResponse([]));
    const mounted = mount(lookupProperty(), {
        webAPI: mockWebApi({ retrieveMultipleRecords }),
    });
    mounted.context.parameters.targetTable.raw = "contact";

    mounted.control.updateView(mounted.context);
    await flushPromises();

    expect(retrieveMultipleRecords).toHaveBeenLastCalledWith(
        "contact",
        "?$select=accountid,accountname&$filter=statecode%20eq%200&$orderby=accountname%20asc",
        25,
    );
});

test("configured target table mismatch with the selected lookup is a visible configuration error", async () => {
    const retrieveMultipleRecords = jest.fn(async (_entityLogicalName: string, _query?: string, _maxPageSize?: number) => createResponse([]));
    const mounted = mount(lookupProperty([
        { id: "33333333-3333-4333-8333-333333333333", name: "Mismatched contact", entityType: "contact" },
    ]), {
        webAPI: mockWebApi({ retrieveMultipleRecords }),
    });

    await flushPromises();

    expect(retrieveMultipleRecords).not.toHaveBeenCalled();
    expect(mounted.select().disabled).toBe(true);
    expect(mounted.status().textContent).toContain("Target table configuration");
});

test("stale lookup loads cannot overwrite a later target mismatch error", async () => {
    const pending = deferredResponse();
    const retrieveMultipleRecords = jest.fn((_entityLogicalName: string, _query?: string, _maxPageSize?: number) => pending.promise);
    const mounted = mount(lookupProperty(), {
        webAPI: mockWebApi({ retrieveMultipleRecords }),
    });
    await flushPromises();

    mounted.context.parameters.lookupValue = lookupProperty([
        { id: "33333333-3333-4333-8333-333333333333", name: "Mismatched contact", entityType: "contact" },
    ]) as IInputs["lookupValue"];
    mounted.control.updateView(mounted.context);
    expect(mounted.status().textContent).toContain("Target table configuration");

    pending.resolve(createResponse([
        { accountid: "11111111-1111-4111-8111-111111111111", accountname: "Stale account" },
    ]));
    await flushPromises();

    expect(mounted.status().textContent).toContain("Target table configuration");
    expect(Array.from(mounted.select().options).map((option) => option.textContent)).not.toContain("Stale account");
});

test("unchanged updateView keeps the in-flight lookup loading status without restarting", async () => {
    const pending = deferredResponse();
    const retrieveMultipleRecords = jest.fn((_entityLogicalName: string, _query?: string, _maxPageSize?: number) => pending.promise);
    const mounted = mount(lookupProperty(), {
        webAPI: mockWebApi({ retrieveMultipleRecords }),
    });
    await flushPromises();

    mounted.control.updateView(mounted.context);
    await flushPromises();

    expect(retrieveMultipleRecords).toHaveBeenCalledTimes(1);
    expect(mounted.status().textContent).toContain("Loading lookup options");
    expect(mounted.status().hidden).toBe(false);

    pending.resolve(createResponse([
        { accountid: "11111111-1111-4111-8111-111111111111", accountname: "Alpha" },
    ]));
    await flushPromises();

    expect(retrieveMultipleRecords).toHaveBeenCalledTimes(1);
    expect(Array.from(mounted.select().options).map((option) => option.textContent)).toContain("Alpha");
});

test("lookup completion respects editability withdrawn while loading", async () => {
    const pending = deferredResponse();
    const retrieveMultipleRecords = jest.fn((_entityLogicalName: string, _query?: string, _maxPageSize?: number) => pending.promise);
    const mounted = mount(lookupProperty(), {
        webAPI: mockWebApi({ retrieveMultipleRecords }),
    });
    await flushPromises();

    mounted.context.parameters.lookupValue = lookupProperty([], { editable: false }) as IInputs["lookupValue"];
    mounted.control.updateView(mounted.context);
    expect(mounted.select().disabled).toBe(true);

    pending.resolve(createResponse([
        { accountid: "11111111-1111-4111-8111-111111111111", accountname: "Alpha" },
    ]));
    await flushPromises();

    expect(mounted.select().disabled).toBe(true);
});

test("destroy drops a stale lookup load without rendering", async () => {
    const pending = deferredResponse();
    const retrieveMultipleRecords = jest.fn((_entityLogicalName: string, _query?: string, _maxPageSize?: number) => pending.promise);
    const mounted = mount(lookupProperty(), {
        webAPI: mockWebApi({ retrieveMultipleRecords }),
    });
    await flushPromises();

    mounted.control.destroy();
    pending.resolve(createResponse([
        { accountid: "11111111-1111-4111-8111-111111111111", accountname: "Stale account" },
    ]));
    await flushPromises();

    expect(mounted.container.childElementCount).toBe(0);
});

test("omits the selectable row filter when the maker leaves configuration blank", async () => {
    const retrieveMultipleRecords = jest.fn(async (_entityLogicalName: string, _query?: string, _maxPageSize?: number) => createResponse([]));
    const mounted = mount(lookupProperty(), {
        webAPI: mockWebApi({ retrieveMultipleRecords }),
    });
    mounted.context.parameters.selectableFilter.raw = "";

    mounted.control.updateView(mounted.context);
    await flushPromises();

    expect(retrieveMultipleRecords).toHaveBeenLastCalledWith(
        "account",
        "?$select=accountid,accountname&$orderby=accountname%20asc",
        25,
    );
});

test("unchanged updateView keeps loaded lookup options and does not restart the query", async () => {
    const retrieveMultipleRecords = jest.fn(async (_entityLogicalName: string, _query?: string, _maxPageSize?: number) => createResponse([
        { accountid: "11111111-1111-4111-8111-111111111111", accountname: "Alpha" },
    ]));
    const mounted = mount(lookupProperty(), {
        webAPI: mockWebApi({ retrieveMultipleRecords }),
    });

    await flushPromises();
    mounted.control.updateView(mounted.context);
    await flushPromises();

    expect(retrieveMultipleRecords).toHaveBeenCalledTimes(1);
    expect(Array.from(mounted.select().options).map((option) => option.textContent)).toContain("Alpha");
});

test("changed lookup query inputs restart lookup loading exactly once", async () => {
    const retrieveMultipleRecords = jest.fn()
        .mockResolvedValueOnce(createResponse([{ accountid: "11111111-1111-4111-8111-111111111111", accountname: "Alpha" }]))
        .mockResolvedValueOnce(createResponse([{ accountid: "22222222-2222-4222-8222-222222222222", accountname: "Beta" }]));
    const mounted = mount(lookupProperty(), {
        webAPI: mockWebApi({ retrieveMultipleRecords }),
    });

    await flushPromises();
    mounted.context.parameters.selectableFilter.raw = "name ne null";
    mounted.control.updateView(mounted.context);
    await flushPromises();

    expect(retrieveMultipleRecords).toHaveBeenCalledTimes(2);
    expect(Array.from(mounted.select().options).map((option) => option.textContent)).toContain("Beta");
    expect(Array.from(mounted.select().options).map((option) => option.textContent)).not.toContain("Alpha");
});

test("lookup loading stops at the documented page cap and reports that more rows exist", async () => {
    const retrieveMultipleRecords = jest.fn(async (_entityLogicalName: string, _query?: string, _maxPageSize?: number) => createResponse([
        { accountid: "11111111-1111-4111-8111-111111111111", accountname: "Alpha" },
    ], "https://contoso.crm.dynamics.com/api/data/v9.2/accounts?$skiptoken=next"));
    const mounted = mount(lookupProperty(), {
        webAPI: mockWebApi({ retrieveMultipleRecords }),
    });

    await flushPromises();

    expect(retrieveMultipleRecords).toHaveBeenCalledTimes(4);
    expect(mounted.status().textContent).toContain("More rows exist");
});

test("unchanged updateView keeps the capped lookup warning without restarting the query", async () => {
    const retrieveMultipleRecords = jest.fn(async (_entityLogicalName: string, _query?: string, _maxPageSize?: number) => createResponse([
        { accountid: "11111111-1111-4111-8111-111111111111", accountname: "Alpha" },
    ], "https://contoso.crm.dynamics.com/api/data/v9.2/accounts?$skiptoken=next"));
    const mounted = mount(lookupProperty(), {
        webAPI: mockWebApi({ retrieveMultipleRecords }),
    });

    await flushPromises();
    mounted.control.updateView(mounted.context);
    await flushPromises();

    expect(retrieveMultipleRecords).toHaveBeenCalledTimes(4);
    expect(mounted.status().textContent).toContain("More rows exist");
});

test("clearing the dropdown returns an empty lookup array and unchanged values do not notify", async () => {
    const mounted = mount(lookupProperty([
        { id: "11111111-1111-4111-8111-111111111111", name: "Alpha", entityType: "account" },
    ]));

    await flushPromises();
    mounted.select().value = "11111111-1111-4111-8111-111111111111";
    mounted.select().dispatchEvent(new Event("change"));
    mounted.select().value = "";
    mounted.select().dispatchEvent(new Event("change"));

    expect(mounted.notify).toHaveBeenCalledTimes(1);
    expect(mounted.control.getOutputs()).toEqual({ lookupValue: [] });
});

test("selected inactive records stay displayed even when the active query excludes them", async () => {
    const mounted = mount(lookupProperty([
        { id: "99999999-9999-4999-8999-999999999999", name: "Retired account", entityType: "account" },
    ]));

    await flushPromises();

    expect(Array.from(mounted.select().options).map((option) => option.textContent)).toContain("Retired account");
    expect(mounted.select().value).toBe("99999999-9999-4999-8999-999999999999");
});

test("missing parameter, disabled mode and security states render safe non-editable UI", async () => {
    const missing = mount(undefined);
    await flushPromises();
    expect(missing.select().disabled).toBe(true);
    expect(missing.status().textContent).toContain("Bind this component");

    const disabled = mount(lookupProperty(), { disabled: true });
    await flushPromises();
    expect(disabled.select().disabled).toBe(true);

    const unreadable = mount(lookupProperty([], { readable: false }));
    await flushPromises();
    expect(unreadable.select().hidden).toBe(true);
    expect(unreadable.status().textContent).toContain("permission");

    const readOnly = mount(lookupProperty([], { editable: false }));
    await flushPromises();
    expect(readOnly.select().disabled).toBe(true);
});

test("unsaved forms still load options because the control does not need a current record id", async () => {
    const retrieveMultipleRecords = jest.fn(async (_entityLogicalName: string, _query?: string, _maxPageSize?: number) => createResponse([
        { accountid: "11111111-1111-4111-8111-111111111111", accountname: "Active account" },
    ]));
    const mounted = mount(lookupProperty(), {
        webAPI: mockWebApi({ retrieveMultipleRecords }),
    });

    await flushPromises();

    expect(retrieveMultipleRecords).toHaveBeenCalled();
    expect(mounted.status().hidden).toBe(true);
});

test("permission failures from Web API are shown without notifying", async () => {
    const mounted = mount(lookupProperty(), {
        webAPI: mockWebApi({
            retrieveMultipleRecords: jest.fn(async (_entityLogicalName: string, _query?: string, _maxPageSize?: number) => {
                throw new Error("Access denied");
            }),
        }),
    });

    await flushPromises();

    expect(mounted.notify).not.toHaveBeenCalled();
    expect(mounted.status().textContent).toContain("Unable to load lookup options");
});

test("two instances keep independent state and notifications", async () => {
    const first = mount(lookupProperty());
    const second = mount(lookupProperty());

    await flushPromises();
    first.select().value = "11111111-1111-4111-8111-111111111111";
    first.select().dispatchEvent(new Event("change"));

    expect(first.notify).toHaveBeenCalledTimes(1);
    expect(second.notify).not.toHaveBeenCalled();
    expect(first.control.getOutputs()).toEqual({
        lookupValue: [{ id: "11111111-1111-4111-8111-111111111111", name: "Active account", entityType: "account" }],
    });
    expect(second.control.getOutputs()).toEqual({ lookupValue: [] });
});