|
1 | | -import { UtcDateFromStringSchema, UtcDateTimeFromStringSchema } from "@src/utils/date"; |
2 | | -import { calculateAge } from "@src/utils/date"; |
| 1 | +import { UtcDateFromStringSchema, UtcDateTimeFromStringSchema, calculateAge, getNow } from "@src/utils/date"; |
| 2 | +import { headers } from "next/headers"; |
| 3 | + |
| 4 | +jest.mock("next/headers"); |
3 | 5 |
|
4 | 6 | describe("utils-date", () => { |
5 | 7 | describe("UtcDateFromStringSchema", () => { |
@@ -64,6 +66,7 @@ describe("utils-date", () => { |
64 | 66 | }).toThrow(); |
65 | 67 | }); |
66 | 68 | }); |
| 69 | + |
67 | 70 | describe("calculateAge", () => { |
68 | 71 | beforeAll(() => { |
69 | 72 | jest.useFakeTimers(); |
@@ -117,4 +120,41 @@ describe("utils-date", () => { |
117 | 120 | }).toThrow(); |
118 | 121 | }); |
119 | 122 | }); |
| 123 | + |
| 124 | + describe("getNow", () => { |
| 125 | + const fakeDateInSystem = "2000-01-01T01:01:01Z"; |
| 126 | + const fakeDateInHeader = "1212-12-12T12:12:12Z"; |
| 127 | + |
| 128 | + beforeEach(() => { |
| 129 | + jest.useFakeTimers(); |
| 130 | + jest.setSystemTime(new Date(fakeDateInSystem)); |
| 131 | + }); |
| 132 | + |
| 133 | + it("should return current date by default", async () => { |
| 134 | + expect(await getNow()).toEqual(new Date(fakeDateInSystem)); |
| 135 | + }); |
| 136 | + |
| 137 | + it("should return date set in the header, when it is valid", async () => { |
| 138 | + const mockHeaders = { |
| 139 | + get: jest.fn(() => { |
| 140 | + return fakeDateInHeader; |
| 141 | + }), |
| 142 | + }; |
| 143 | + (headers as jest.Mock).mockResolvedValue(mockHeaders); |
| 144 | + |
| 145 | + expect(await getNow()).toEqual(new Date(fakeDateInHeader)); |
| 146 | + }); |
| 147 | + |
| 148 | + it("should return current date when date set in the header is malformed", async () => { |
| 149 | + const fakeDateInHeaderInvalid = "invalid-date"; |
| 150 | + const mockHeaders = { |
| 151 | + get: jest.fn(() => { |
| 152 | + return fakeDateInHeaderInvalid; |
| 153 | + }), |
| 154 | + }; |
| 155 | + (headers as jest.Mock).mockResolvedValue(mockHeaders); |
| 156 | + |
| 157 | + expect(await getNow()).toEqual(new Date(fakeDateInSystem)); |
| 158 | + }); |
| 159 | + }); |
120 | 160 | }); |
0 commit comments