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', () => {
describe('formatDate', () => {
it('returns absolute formatted date', () => {
// nb. Date has no time zone specifier so is assumed to be in the current
// time zone.
const date = new Date('2020-05-04T03:02:01');
const date = new Date('2020-05-04T23:02:01');
const fakeIntl = locale => ({
DateTimeFormat: function (_, options) {
return new Intl.DateTimeFormat(locale, options);
},
});
assert.equal(
formatDate(date, fakeIntl('en-US')),
'Monday, May 04, 2020, 11:02 PM'
);
const formatted = formatDate(date);
clearFormatters();
// The exact format will depend on the system locale and browser, but it
// should contain at least the following tokens.
const tokens = ['2020', '04', '03', '02'];
tokens.forEach(token =>
assert.match(formatted, new RegExp(`\\b${token}\\b`))
assert.equal(
formatDate(date, fakeIntl('de-DE')),
'Montag, 04. Mai 2020, 23:02'
);
});
});
......
......@@ -257,15 +257,20 @@ export function formatRelativeDate(date, now, Intl) {
* "Sunday, Dec 17, 2017, 10:00 AM"
*
* @param {Date} date
* @param {Intl} [Intl] - Test seam. JS `Intl` API implementation.
* @return {string}
*/
export function formatDate(date) {
return format(date, {
year: 'numeric',
month: 'short',
day: '2-digit',
weekday: 'long',
hour: '2-digit',
minute: '2-digit',
});
export function formatDate(date, Intl) {
return format(
date,
{
year: 'numeric',
month: 'short',
day: '2-digit',
weekday: 'long',
hour: '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