93 lines
2.6 KiB
TypeScript
93 lines
2.6 KiB
TypeScript
import { render, screen } from "@testing-library/react";
|
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
|
|
// Mock the Unleash React SDK: capture provider props, control flag state.
|
|
const sdk = vi.hoisted(() => ({
|
|
on: new Set<string>(),
|
|
providerProps: [] as Record<string, unknown>[],
|
|
}));
|
|
vi.mock("@unleash/proxy-client-react", () => ({
|
|
FlagProvider: (props: { children: React.ReactNode }) => {
|
|
sdk.providerProps.push(props);
|
|
return props.children;
|
|
},
|
|
useFlag: (name: string) => sdk.on.has(name),
|
|
useVariant: () => ({ name: "disabled", enabled: false }),
|
|
}));
|
|
|
|
import { FlagsProvider, unleashConfig, useFlag } from "./flags";
|
|
|
|
function Probe() {
|
|
return <p>{useFlag("hello-banner") ? "on" : "off"}</p>;
|
|
}
|
|
|
|
beforeEach(() => {
|
|
sdk.on.clear();
|
|
sdk.providerProps.length = 0;
|
|
});
|
|
|
|
describe("unleashConfig", () => {
|
|
const base = { API_BASE_URL: "/api", APP_NAME: "web" };
|
|
it("is null when UNLEASH_URL or token is unset", () => {
|
|
expect(
|
|
unleashConfig({ ...base, UNLEASH_URL: "", UNLEASH_FRONTEND_TOKEN: "" }),
|
|
).toBeNull();
|
|
expect(
|
|
unleashConfig({
|
|
...base,
|
|
UNLEASH_URL: "http://u",
|
|
UNLEASH_FRONTEND_TOKEN: "",
|
|
}),
|
|
).toBeNull();
|
|
});
|
|
it("points at the Frontend API", () => {
|
|
expect(
|
|
unleashConfig({
|
|
...base,
|
|
UNLEASH_URL: "http://unleash.test/",
|
|
UNLEASH_FRONTEND_TOKEN: "*:development.x",
|
|
}),
|
|
).toMatchObject({
|
|
url: "http://unleash.test/api/frontend",
|
|
clientKey: "*:development.x",
|
|
appName: "web",
|
|
});
|
|
});
|
|
});
|
|
|
|
describe("FlagsProvider", () => {
|
|
it("starts the client when configured", () => {
|
|
window.__APP_CONFIG__ = {
|
|
APP_NAME: "web",
|
|
UNLEASH_URL: "http://unleash.test",
|
|
UNLEASH_FRONTEND_TOKEN: "tok",
|
|
};
|
|
sdk.on.add("hello-banner");
|
|
render(
|
|
<FlagsProvider>
|
|
<Probe />
|
|
</FlagsProvider>,
|
|
);
|
|
expect(screen.getByText("on")).toBeInTheDocument();
|
|
expect(sdk.providerProps[0]).toMatchObject({
|
|
startClient: true,
|
|
config: { url: "http://unleash.test/api/frontend", clientKey: "tok" },
|
|
});
|
|
});
|
|
|
|
it("stays offline when UNLEASH_URL is unset", () => {
|
|
window.__APP_CONFIG__ = { APP_NAME: "web" };
|
|
const info = vi.spyOn(console, "info").mockImplementation(() => {});
|
|
render(
|
|
<FlagsProvider>
|
|
<Probe />
|
|
</FlagsProvider>,
|
|
);
|
|
expect(screen.getByText("off")).toBeInTheDocument();
|
|
expect(sdk.providerProps[0]).toMatchObject({
|
|
startClient: false,
|
|
config: { disableRefresh: true, disableMetrics: true },
|
|
});
|
|
expect(info).toHaveBeenCalledTimes(1);
|
|
});
|
|
});
|