rewardsBridge.test.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import { runInNewContext } from "node:vm";
  2. import { expect, it } from "vitest";
  3. import { installRewardsPageBridge, createRewardsInjectionScript } from "@zcode/shared";
  4. it("bridge 保留当前快照、通知及退订,凭据不出现在事件中", () => {
  5. const window = new EventTarget() as EventTarget & { zcodeBridge: any };
  6. const values = new Map<string, string>([["oauth:bigmodel:access_token", "old-account"]]);
  7. const context = {
  8. window,
  9. CustomEvent,
  10. localStorage: {
  11. setItem: (k: string, v: string) => values.set(k, v),
  12. removeItem: (k: string) => values.delete(k),
  13. },
  14. };
  15. runInNewContext(`(${installRewardsPageBridge.toString()})()`, context);
  16. expect(values.size).toBe(0);
  17. const bridge = window.zcodeBridge;
  18. expect(bridge.getTheme()).toBeNull();
  19. const themes: string[] = [];
  20. const off = bridge.onThemeChange((value: string) => themes.push(value));
  21. const snapshot = {
  22. theme: "zai-light" as const,
  23. locale: "en-US" as const,
  24. auth: { status: "ready" as const, provider: "zai" as const, revision: 1 },
  25. };
  26. window.dispatchEvent(new CustomEvent("zcode-referrals-context", { detail: snapshot }));
  27. expect(bridge.getTheme()).toBeNull();
  28. expect(bridge.getAuthState()).toBeNull();
  29. runInNewContext(
  30. createRewardsInjectionScript(snapshot, { oauth: "fixture-token", jwt: "fixture-jwt" }),
  31. context,
  32. );
  33. expect(themes).toEqual(["zai-light"]);
  34. expect(bridge.getAuthState()).toEqual(snapshot.auth);
  35. expect(values.get("oauth:zai:access_token")).toBe("fixture-token");
  36. off();
  37. runInNewContext(
  38. createRewardsInjectionScript(
  39. {
  40. ...snapshot,
  41. theme: "zai-dark",
  42. auth: { status: "anonymous", provider: null, revision: 2 },
  43. },
  44. {},
  45. ),
  46. context,
  47. );
  48. expect(themes).toEqual(["zai-light"]);
  49. expect(bridge.getTheme()).toBe("zai-dark");
  50. expect(values.size).toBe(0);
  51. expect(bridge.notifyPurchaseComplete).toBeUndefined();
  52. });