Commit 3b9a71b3 authored by Robert Knight's avatar Robert Knight

Use mock `Intl` to test `formatDate` in tests

This uses the real `Intl.DateTimeFormat` API but with a fixed locale to
ensure consistent output across systems. This is a more complete test
than the previous one.

The test assumes that output is consistent across browsers for the date
given. In testing with Safari, Firefox and Chrome this was the case for
the en-US locale. We accept some small risk that the exact format might change
slightly in future releases of one of these browsers.
parent d821b116
...@@ -230,17 +230,23 @@ describe('sidebar/util/time', () => { ...@@ -230,17 +230,23 @@ describe('sidebar/util/time', () => {
describe('formatDate', () => { describe('formatDate', () => {
it('returns absolute formatted date', () => { it('returns absolute formatted date', () => {
// nb. Date has no time zone specifier so is assumed to be in the current const date = new Date('2020-05-04T23:02:01');
// time zone. const fakeIntl = locale => ({
const date = new Date('2020-05-04T03:02:01'); DateTimeFormat: function (_, options) {
return new Intl.DateTimeFormat(locale, options);
},
});
const formatted = formatDate(date); assert.equal(
formatDate(date, fakeIntl('en-US')),
'Monday, May 04, 2020, 11:02 PM'
);
clearFormatters();
// The exact format will depend on the system locale and browser, but it assert.equal(
// should contain at least the following tokens. formatDate(date, fakeIntl('de-DE')),
const tokens = ['2020', '04', '03', '02']; 'Montag, 04. Mai 2020, 23:02'
tokens.forEach(token =>
assert.match(formatted, new RegExp(`\\b${token}\\b`))
); );
}); });
}); });
......
...@@ -257,15 +257,20 @@ export function formatRelativeDate(date, now, Intl) { ...@@ -257,15 +257,20 @@ export function formatRelativeDate(date, now, Intl) {
* "Sunday, Dec 17, 2017, 10:00 AM" * "Sunday, Dec 17, 2017, 10:00 AM"
* *
* @param {Date} date * @param {Date} date
* @param {Intl} [Intl] - Test seam. JS `Intl` API implementation.
* @return {string} * @return {string}
*/ */
export function formatDate(date) { export function formatDate(date, Intl) {
return format(date, { return format(
date,
{
year: 'numeric', year: 'numeric',
month: 'short', month: 'short',
day: '2-digit', day: '2-digit',
weekday: 'long', weekday: 'long',
hour: '2-digit', hour: '2-digit',
minute: '2-digit', minute: '2-digit',
}); },
Intl
);
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment