v4MessageTimeLabel.test.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import { describe, expect, it } from "vitest";
  2. import type { IntlInstance } from "@/i18n/IntlProvider.js";
  3. import { formatMessageTimeLabel } from "@/v4/messageTimeLabel.js";
  4. function createIntl(yesterdayLabel: string): IntlInstance {
  5. return {
  6. formatMessage({ id }, values) {
  7. if (id === "chat.message.time.yesterday") {
  8. return `${yesterdayLabel} ${values?.time ?? ""}`.trim();
  9. }
  10. return id;
  11. },
  12. };
  13. }
  14. function formatExpected(
  15. locale: string,
  16. timestamp: number,
  17. options: Intl.DateTimeFormatOptions,
  18. ): string {
  19. return new Intl.DateTimeFormat(locale, options).format(new Date(timestamp));
  20. }
  21. describe("formatMessageTimeLabel", () => {
  22. const now = new Date(2026, 6, 13, 12, 0).getTime();
  23. const zhIntl = createIntl("昨天");
  24. const enIntl = createIntl("Yesterday");
  25. it("当天只显示本地时分", () => {
  26. const timestamp = new Date(2026, 6, 13, 7, 15).getTime();
  27. expect(formatMessageTimeLabel(timestamp, "zh-CN", zhIntl, now)).toBe(
  28. formatExpected("zh-CN", timestamp, { hour: "2-digit", minute: "2-digit" }),
  29. );
  30. });
  31. it.each([
  32. ["zh-CN", zhIntl, "昨天"],
  33. ["en-US", enIntl, "Yesterday"],
  34. ] as const)("%s 为昨天的消息加本地化前缀", (locale, intl, prefix) => {
  35. const timestamp = new Date(2026, 6, 12, 7, 15).getTime();
  36. const time = formatExpected(locale, timestamp, { hour: "2-digit", minute: "2-digit" });
  37. expect(formatMessageTimeLabel(timestamp, locale, intl, now)).toBe(`${prefix} ${time}`);
  38. });
  39. it("当年更早的消息显示月日和时分", () => {
  40. const timestamp = new Date(2026, 3, 10, 7, 15).getTime();
  41. expect(formatMessageTimeLabel(timestamp, "zh-CN", zhIntl, now)).toBe(
  42. formatExpected("zh-CN", timestamp, {
  43. month: "numeric",
  44. day: "numeric",
  45. hour: "2-digit",
  46. minute: "2-digit",
  47. }),
  48. );
  49. });
  50. it("跨年消息显示年月日和时分", () => {
  51. const timestamp = new Date(2025, 11, 31, 7, 15).getTime();
  52. expect(formatMessageTimeLabel(timestamp, "en-US", enIntl, now)).toBe(
  53. formatExpected("en-US", timestamp, {
  54. year: "numeric",
  55. month: "numeric",
  56. day: "numeric",
  57. hour: "2-digit",
  58. minute: "2-digit",
  59. }),
  60. );
  61. });
  62. it.each([0, -1, Number.NaN, Number.POSITIVE_INFINITY])("无效时间戳 %s 不展示", (timestamp) => {
  63. expect(formatMessageTimeLabel(timestamp, "zh-CN", zhIntl, now)).toBeNull();
  64. });
  65. });