longTaskAttributionSummary.test.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import { describe, expect, it } from "vitest";
  2. import { summarizeLongTaskAttribution } from "../src/main/longTaskAttributionSummary.js";
  3. describe("summarizeLongTaskAttribution", () => {
  4. it("提炼耗时最长的 attribution 作为 top,并计算占比", () => {
  5. const snapshots = JSON.stringify([
  6. { duration: 40, invokerType: "event-listener" },
  7. { duration: 120, invokerType: "user-callback" },
  8. { duration: 10, invokerType: "user-callback" },
  9. ]);
  10. const result = summarizeLongTaskAttribution(snapshots, 200);
  11. expect(result).toEqual({
  12. loaf_script_count: 3,
  13. loaf_top_duration_ms: 120,
  14. loaf_top_invoker_type: "user-callback",
  15. loaf_top_share_pct: 60,
  16. });
  17. });
  18. it("snapshots 为空字符串时返回 null", () => {
  19. expect(summarizeLongTaskAttribution("", 200)).toBeNull();
  20. });
  21. it("snapshots 为 '[]' 时返回 null", () => {
  22. expect(summarizeLongTaskAttribution("[]", 200)).toBeNull();
  23. });
  24. it("snapshots 非法 JSON 时返回 null", () => {
  25. expect(summarizeLongTaskAttribution("{not valid json", 200)).toBeNull();
  26. });
  27. it("snapshots 为 undefined 时返回 null", () => {
  28. expect(summarizeLongTaskAttribution(undefined, 200)).toBeNull();
  29. });
  30. it("invokerType 缺失时归一化为 script(rAF 来源)", () => {
  31. const snapshots = JSON.stringify([{ duration: 50, containerType: "iframe" }]);
  32. const result = summarizeLongTaskAttribution(snapshots, 100);
  33. expect(result?.loaf_top_invoker_type).toBe("script");
  34. });
  35. it("invokerType 为非法枚举值时归一化为 unknown", () => {
  36. const snapshots = JSON.stringify([{ duration: 50, invokerType: "weird-value" }]);
  37. const result = summarizeLongTaskAttribution(snapshots, 100);
  38. expect(result?.loaf_top_invoker_type).toBe("unknown");
  39. });
  40. it("totalDurationMs 为 0/负数/非数字时 share 记 0,其它字段仍正常", () => {
  41. const snapshots = JSON.stringify([{ duration: 50, invokerType: "user-callback" }]);
  42. for (const total of [0, -10, Number.NaN, "not-a-number", undefined]) {
  43. const result = summarizeLongTaskAttribution(snapshots, total);
  44. expect(result).not.toBeNull();
  45. expect(result?.loaf_top_share_pct).toBe(0);
  46. expect(result?.loaf_top_duration_ms).toBe(50);
  47. }
  48. });
  49. });