people: Fix misleading comments and tests for utcToZonedTime.

The reason utcToZonedTime would return an invalid Date (i.e. ‘new
Date(NaN)’) is because we passed in an invalid timezone.  Fix the
comments and tests to reflect this; remove unnecessary mocking and the
misleading ‘instanceof Date’ check.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
This commit is contained in:
Anders Kaseorg 2022-11-23 13:46:45 -08:00 committed by Tim Abbott
parent 2d1d8ac550
commit 2cf64b569e
2 changed files with 5 additions and 16 deletions

View File

@ -3,7 +3,6 @@
const {strict: assert} = require("assert");
const {parseISO} = require("date-fns");
const date_fns_tz = require("date-fns-tz");
const _ = require("lodash");
const MockDate = require("mockdate");
@ -520,14 +519,10 @@ test_people("utcToZonedTime", ({override}) => {
MockDate.set(parseISO("20130208T080910").getTime());
user_settings.twenty_four_hour_time = true;
override(date_fns_tz, "utcToZonedTime", () => new Date("2022/10/10 03:24"));
assert.equal(people.get_user_time(me.user_id), "3:24");
assert.equal(people.get_user_time(me.user_id), "0:09");
override(date_fns_tz, "utcToZonedTime", () => new Date("foo"));
blueslip.expect("error", "Got invalid date for timezone: America/Los_Angeles", 2);
people.get_user_time(me.user_id);
override(date_fns_tz, "utcToZonedTime", () => undefined);
override(people.get_by_user_id(me.user_id), "timezone", "Eriador/Rivendell");
blueslip.expect("error", "Got invalid date for timezone: Eriador/Rivendell");
people.get_user_time(me.user_id);
});

View File

@ -287,14 +287,8 @@ export function get_user_time(user_id) {
const user_pref = get_user_time_preferences(user_id);
if (user_pref) {
const current_date = utcToZonedTime(new Date(), user_pref.timezone);
// In theory, utcToZonedTime should always return a Date
// object. However, we have reports from users in the wild
// seeing this returning `undefined`. To avoid throwing an
// exception, we check whether we got a Date object back,
// including a NaN check, which covers the case where we
// called `Date("foo")`.
// eslint-disable-next-line unicorn/prefer-number-properties
if (!(current_date instanceof Date) || isNaN(current_date)) {
// This could happen if the timezone is invalid.
if (Number.isNaN(current_date.getTime())) {
blueslip.error(`Got invalid date for timezone: ${user_pref.timezone}`);
return undefined;
}