返回 CodeWhale
detect.test.ts
根目录 / web / lib / i18n / detect.test.ts
1 import { describe, expect, it } from "vitest";
2 import { detectLocaleFromHeaders, matchLocaleTag } from "./detect";
3
4 describe("matchLocaleTag", () => {
5 it("matches exact full tags case-insensitively", () => {
6 expect(matchLocaleTag("pt-BR")).toBe("pt-BR");
7 expect(matchLocaleTag("PT-br")).toBe("pt-BR");
8 expect(matchLocaleTag("ru")).toBe("ru");
9 expect(matchLocaleTag("uk")).toBe("uk");
10 });
11
12 it("maps regional variants to the routed base tag", () => {
13 expect(matchLocaleTag("ru-RU")).toBe("ru");
14 expect(matchLocaleTag("uk-UA")).toBe("uk");
15 expect(matchLocaleTag("es-MX")).toBe("es");
16 expect(matchLocaleTag("es-419")).toBe("es");
17 expect(matchLocaleTag("zh-Hant")).toBe("zh");
18 expect(matchLocaleTag("zh-TW")).toBe("zh");
19 expect(matchLocaleTag("ja-JP")).toBe("ja");
20 expect(matchLocaleTag("ko-KR")).toBe("ko");
21 expect(matchLocaleTag("vi-VN")).toBe("vi");
22 expect(matchLocaleTag("id-ID")).toBe("id");
23 });
24
25 it("routes pt to the only shipped Portuguese variant", () => {
26 expect(matchLocaleTag("pt")).toBe("pt-BR");
27 expect(matchLocaleTag("pt-PT")).toBe("pt-BR");
28 });
29
30 it("rejects unrouted and empty tags deterministically", () => {
31 expect(matchLocaleTag("fr")).toBeNull();
32 expect(matchLocaleTag("de-DE")).toBeNull();
33 expect(matchLocaleTag("ar")).toBeNull();
34 expect(matchLocaleTag("")).toBeNull();
35 expect(matchLocaleTag("*")).toBeNull();
36 });
37 });
38
39 describe("detectLocaleFromHeaders", () => {
40 it("prefers an explicit cookie choice over Accept-Language", () => {
41 expect(detectLocaleFromHeaders("ru", "ja,en;q=0.8")).toBe("ru");
42 });
43
44 it("ignores stale cookies for unrouted locales", () => {
45 expect(detectLocaleFromHeaders("fr", "uk,en;q=0.8")).toBe("uk");
46 });
47
48 it("honors Accept-Language preference order", () => {
49 expect(detectLocaleFromHeaders(undefined, "fr,vi;q=0.9,ru;q=0.8")).toBe("vi");
50 expect(detectLocaleFromHeaders(undefined, "de,pt;q=0.7")).toBe("pt-BR");
51 });
52
53 it("falls back to the default locale with no signal", () => {
54 expect(detectLocaleFromHeaders(undefined, null)).toBe("en");
55 expect(detectLocaleFromHeaders(undefined, "")).toBe("en");
56 expect(detectLocaleFromHeaders(undefined, "fr,de;q=0.8")).toBe("en");
57 });
58 });
59
59 lines TYPESCRIPT