Files
role-user/tests/growth-analytics.test.mjs
T
湛兮 a580422100 feat(growth): 接入游客推荐与权益体验
- 登录:新增游客体验、登录承接和同源及请求体积校验
- 推荐与埋点:接入曝光回执、兴趣偏好和按账号隔离的重试队列
- 聊天体验:展示剩余额度、支持回答反馈及故事记忆管理
- 文档和测试:同步业务边界,覆盖队列幂等与代理登录校验
2026-10-28 21:17:45 +08:00

130 lines
4.7 KiB
JavaScript

/** 事件队列使用可控浏览器存储与HTTP夹具,验证批次边界、重试和账号切换。 */
import test from "node:test";
import assert from "node:assert/strict";
import {
trackGrowth,
flushGrowth,
rememberRecommendation,
recommendationReceipt,
} from "../src/lib/growth-analytics.ts";
function storage(t) {
const values = new Map();
if (!("sessionStorage" in globalThis))
Object.defineProperty(globalThis, "sessionStorage", {
value: undefined,
writable: true,
configurable: true,
});
t.mock.property(globalThis, "sessionStorage", {
getItem: (key) => values.get(key) ?? null,
setItem: (key, value) => values.set(key, value),
});
return values;
}
test("账号队列隔离,并将账号绑定到上报批次供服务端核验", async (t) => {
storage(t);
const sent = [];
t.mock.method(globalThis, "fetch", async (_url, init) => {
sent.push(JSON.parse(init.body));
return new Response("{}");
});
trackGrowth("user:1", "page_view", "discover");
trackGrowth("user:2", "card_open", "role");
await flushGrowth("user:1");
assert.equal(sent[0].account, "user:1");
assert.equal(sent[0].events.length, 1);
assert.equal(sent[0].events[0].event, "page_view");
await flushGrowth("user:2");
assert.equal(sent[1].account, "user:2");
});
test("失败重试保留同一个事件UUID,不重新记一次曝光", async (t) => {
storage(t);
const sent = [];
t.mock.method(globalThis, "fetch", async (_url, init) => {
sent.push(JSON.parse(init.body));
return new Response("{}", { status: sent.length === 1 ? 503 : 200 });
});
trackGrowth("user:retry", "card_impression", "role");
await flushGrowth("user:retry");
await flushGrowth("user:retry");
assert.equal(sent.length, 2);
assert.equal(sent[0].events[0].id, sent[1].events[0].id);
await flushGrowth("user:retry");
assert.equal(sent.length, 2);
});
test("一批最多20条,成功响应不丢失请求期间新入队的事件", async (t) => {
const values = storage(t);
const sent = [];
t.mock.method(globalThis, "fetch", async (_url, init) => {
sent.push(JSON.parse(init.body));
trackGrowth("user:batch", "card_open", "new");
return new Response("{}");
});
for (let i = 0; i < 25; i++)
trackGrowth("user:batch", "card_impression", `role-${i}`);
await flushGrowth("user:batch");
assert.equal(sent[0].events.length, 20);
const left = JSON.parse(values.get("dh-events:user:batch"));
assert.equal(left.length, 6);
assert.equal(left.at(-1).entity, "new");
});
test("无效批次停止重试,未授权与暂时失败不直接丢弃", async (t) => {
const values = storage(t);
let code = 401;
t.mock.method(
globalThis,
"fetch",
async () => new Response("{}", { status: code }),
);
trackGrowth("user:invalid", "page_view", "discover");
await flushGrowth("user:invalid");
assert.equal(JSON.parse(values.get("dh-events:user:invalid")).length, 1);
code = 400;
await flushGrowth("user:invalid");
assert.equal(JSON.parse(values.get("dh-events:user:invalid")).length, 0);
});
test("推荐回执按账号角色隔离,过期后不再用于新故事归因", (t) => {
const values = storage(t);
rememberRecommendation("u", "card", "receipt");
assert.equal(recommendationReceipt("u", "card"), "receipt");
assert.equal(recommendationReceipt("other", "card"), undefined);
values.set(
"dh-recommendation:u:card",
JSON.stringify({ id: "expired", until: Date.now() - 100 }),
);
assert.equal(recommendationReceipt("u", "card"), undefined);
});
import { sameOriginRequest } from "../src/lib/auth-origin.ts";
test("代理下公网Host可登录,跨站Origin和缺失Origin被拒绝", () => {
const make = (origin, host = "mrzhan.top") =>
new Request("http://127.0.0.1:3210/api/auth/login", {
headers: { host, ...(origin ? { origin } : {}) },
});
assert.equal(sameOriginRequest(make("https://mrzhan.top")), true);
for (const origin of [
"https://evil.test",
"null",
"https://mrzhan.top/path",
"https://mrzhan.top.evil.test",
undefined,
])
assert.equal(sameOriginRequest(make(origin)), false);
});
import { readLoginInput } from "../src/lib/auth-input.ts";
test("登录公开入口限制真实字节数,不先无界解析JSON", async () => {
const request = (body) =>
new Request("http://localhost/api/auth/login", { method: "POST", body });
assert.deepEqual(
await readLoginInput(request('{"username":"user","password":"fixture"}')),
{ username: "user", password: "fixture" },
);
await assert.rejects(
readLoginInput(request(JSON.stringify({ username: "a".repeat(9000) }))),
RangeError,
);
for (const body of ["null", "[]", "invalid"])
await assert.rejects(readLoginInput(request(body)), SyntaxError);
});