71 lines
3.2 KiB
TypeScript
71 lines
3.2 KiB
TypeScript
import { describe, expect, it } from "vitest";
|
|
|
|
import { summarize } from "./analytics.server";
|
|
import type { AnalyticsEvent } from "./analytics-types";
|
|
|
|
const NOW = Date.parse("2026-10-29T10:00:00.000Z");
|
|
|
|
function event(partial: Partial<AnalyticsEvent>): AnalyticsEvent {
|
|
return {
|
|
type: "search",
|
|
at: "2026-10-29T09:00:00.000Z",
|
|
visitor: "v1",
|
|
locale: "th",
|
|
...partial,
|
|
};
|
|
}
|
|
|
|
describe("summarize", () => {
|
|
const events: AnalyticsEvent[] = [
|
|
event({ query: "House Samyan", result_count: 1 }),
|
|
event({ query: "house samyan", result_count: 1 }),
|
|
event({ query: "ไม่มีโรงนี้", result_count: 0, visitor: "v2" }),
|
|
event({ query: "อาร์ตเฮาส์", category: "อาร์ตเฮาส์", result_count: 2 }),
|
|
event({ type: "cinema_select", slug: "house-cinema-samyan", source: "search", query: "house samyan" }),
|
|
event({ type: "cinema_view", slug: "house-cinema-samyan" }),
|
|
event({ type: "near_me", result_count: 6 }),
|
|
// เก่าเกินช่วง 7 วัน — ต้องไม่ถูกนับ
|
|
event({ query: "เก่ามาก", at: "2026-10-01T09:00:00.000Z" }),
|
|
];
|
|
|
|
const summary = summarize(events, 7, NOW);
|
|
|
|
it("นับเฉพาะ event ในช่วงเวลา", () => {
|
|
expect(summary.total_searches).toBe(4);
|
|
});
|
|
|
|
it("นับผู้เข้าชมไม่ซ้ำจาก hash", () => {
|
|
expect(summary.unique_visitors).toBe(2);
|
|
});
|
|
|
|
it("รวมคำค้นที่ต่างแค่ช่องว่าง/ตัวพิมพ์ และนับครั้งที่ค้นไม่พบ", () => {
|
|
const house = summary.top_queries.find((row) => row.query === "house samyan");
|
|
expect(house?.count).toBe(2);
|
|
expect(summary.top_queries.find((row) => row.query === "ไม่มีโรงนี้")?.zero_result_count).toBe(1);
|
|
expect(summary.zero_result_searches).toBe(1);
|
|
});
|
|
|
|
it("นับคลิกต่อคำค้นและการเปิดดูโรงหนัง", () => {
|
|
const house = summary.top_queries.find((row) => row.query === "house samyan");
|
|
expect(house?.click_count).toBe(1);
|
|
const cinema = summary.top_cinemas.find((row) => row.slug === "house-cinema-samyan");
|
|
expect(cinema).toEqual({ slug: "house-cinema-samyan", views: 1, selects: 1 });
|
|
});
|
|
|
|
it("สรุปจำนวนครั้งที่ใช้ ใกล้ฉัน และ CTR", () => {
|
|
expect(summary.near_me_uses).toBe(1);
|
|
expect(summary.click_through_rate).toBe(25);
|
|
});
|
|
|
|
it("ผลลัพธ์เฉลี่ยต่อการค้นหา", () => {
|
|
expect(summary.average_results).toBe(1);
|
|
});
|
|
|
|
it("คำค้นล่าสุดเรียงจากใหม่ไปเก่าและตัด event นอกช่วงออก", () => {
|
|
expect(summary.recent_searches.length).toBeGreaterThan(0);
|
|
const times = summary.recent_searches.map((row) => row.at);
|
|
expect([...times].sort((a, b) => b.localeCompare(a))).toEqual(times);
|
|
expect(summary.recent_searches.some((row) => row.query === "เก่ามาก")).toBe(false);
|
|
});
|
|
});
|