datetime_utility_spec.js 16.2 KB
Newer Older
1
import { __, s__ } from '~/locale';
Clement Ho's avatar
Clement Ho committed
2
import * as datetimeUtility from '~/lib/utils/datetime_utility';
3

4 5
describe('Date time utils', () => {
  describe('timeFor', () => {
6
    it('returns localize `past due` when in past', () => {
7 8 9
      const date = new Date();
      date.setFullYear(date.getFullYear() - 1);

10
      expect(datetimeUtility.timeFor(date)).toBe(s__('Timeago|Past due'));
11 12
    });

13
    it('returns localized remaining time when in the future', () => {
14 15 16 17 18 19
      const date = new Date();
      date.setFullYear(date.getFullYear() + 1);

      // Add a day to prevent a transient error. If date is even 1 second
      // short of a full year, timeFor will return '11 months remaining'
      date.setDate(date.getDate() + 1);
20

21
      expect(datetimeUtility.timeFor(date)).toBe(s__('Timeago|1 year remaining'));
22 23
    });
  });
24

25
  describe('get localized day name', () => {
26 27
    it('should return Sunday', () => {
      const day = datetimeUtility.getDayName(new Date('07/17/2016'));
28

29
      expect(day).toBe(__('Sunday'));
30 31 32 33
    });

    it('should return Monday', () => {
      const day = datetimeUtility.getDayName(new Date('07/18/2016'));
34

35
      expect(day).toBe(__('Monday'));
36 37 38 39
    });

    it('should return Tuesday', () => {
      const day = datetimeUtility.getDayName(new Date('07/19/2016'));
40

41
      expect(day).toBe(__('Tuesday'));
42 43 44 45
    });

    it('should return Wednesday', () => {
      const day = datetimeUtility.getDayName(new Date('07/20/2016'));
46

47
      expect(day).toBe(__('Wednesday'));
48 49 50 51
    });

    it('should return Thursday', () => {
      const day = datetimeUtility.getDayName(new Date('07/21/2016'));
52

53
      expect(day).toBe(__('Thursday'));
54 55 56 57
    });

    it('should return Friday', () => {
      const day = datetimeUtility.getDayName(new Date('07/22/2016'));
58

59
      expect(day).toBe(__('Friday'));
60 61 62 63
    });

    it('should return Saturday', () => {
      const day = datetimeUtility.getDayName(new Date('07/23/2016'));
64

65
      expect(day).toBe(__('Saturday'));
Clement Ho's avatar
Clement Ho committed
66 67 68
    });
  });

69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
  describe('formatDate', () => {
    it('should format date properly', () => {
      const formattedDate = datetimeUtility.formatDate(new Date('07/23/2016'));

      expect(formattedDate).toBe('Jul 23, 2016 12:00am GMT+0000');
    });

    it('should format ISO date properly', () => {
      const formattedDate = datetimeUtility.formatDate('2016-07-23T00:00:00.559Z');

      expect(formattedDate).toBe('Jul 23, 2016 12:00am GMT+0000');
    });

    it('should throw an error if date is invalid', () => {
      expect(() => {
        datetimeUtility.formatDate('2016-07-23 00:00:00 UTC');
      }).toThrow(new Error('Invalid date'));
    });
  });

89 90 91 92 93
  describe('get day difference', () => {
    it('should return 7', () => {
      const firstDay = new Date('07/01/2016');
      const secondDay = new Date('07/08/2016');
      const difference = datetimeUtility.getDayDifference(firstDay, secondDay);
94

95 96
      expect(difference).toBe(7);
    });
Clement Ho's avatar
Clement Ho committed
97

98 99 100 101
    it('should return 31', () => {
      const firstDay = new Date('07/01/2016');
      const secondDay = new Date('08/01/2016');
      const difference = datetimeUtility.getDayDifference(firstDay, secondDay);
102

103
      expect(difference).toBe(31);
Clement Ho's avatar
Clement Ho committed
104 105
    });

106 107 108 109
    it('should return 365', () => {
      const firstDay = new Date('07/02/2015');
      const secondDay = new Date('07/01/2016');
      const difference = datetimeUtility.getDayDifference(firstDay, secondDay);
110

111
      expect(difference).toBe(365);
112 113
    });
  });
114 115 116 117
});

describe('timeIntervalInWords', () => {
  it('should return string with number of minutes and seconds', () => {
118 119 120 121
    expect(datetimeUtility.timeIntervalInWords(9.54)).toEqual(s__('Timeago|9 seconds'));
    expect(datetimeUtility.timeIntervalInWords(1)).toEqual(s__('Timeago|1 second'));
    expect(datetimeUtility.timeIntervalInWords(200)).toEqual(s__('Timeago|3 minutes 20 seconds'));
    expect(datetimeUtility.timeIntervalInWords(6008)).toEqual(s__('Timeago|100 minutes 8 seconds'));
122 123 124 125 126 127 128
  });
});

describe('dateInWords', () => {
  const date = new Date('07/01/2016');

  it('should return date in words', () => {
129
    expect(datetimeUtility.dateInWords(date)).toEqual(s__('July 1, 2016'));
130 131 132
  });

  it('should return abbreviated month name', () => {
133
    expect(datetimeUtility.dateInWords(date, true)).toEqual(s__('Jul 1, 2016'));
134
  });
135 136

  it('should return date in words without year', () => {
137
    expect(datetimeUtility.dateInWords(date, true, true)).toEqual(s__('Jul 1'));
138 139 140 141 142 143 144
  });
});

describe('monthInWords', () => {
  const date = new Date('2017-01-20');

  it('returns month name from provided date', () => {
145
    expect(datetimeUtility.monthInWords(date)).toBe(s__('January'));
146 147 148
  });

  it('returns abbreviated month name from provided date', () => {
149
    expect(datetimeUtility.monthInWords(date, true)).toBe(s__('Jan'));
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
  });
});

describe('totalDaysInMonth', () => {
  it('returns number of days in a month for given date', () => {
    // 1st Feb, 2016 (leap year)
    expect(datetimeUtility.totalDaysInMonth(new Date(2016, 1, 1))).toBe(29);

    // 1st Feb, 2017
    expect(datetimeUtility.totalDaysInMonth(new Date(2017, 1, 1))).toBe(28);

    // 1st Jan, 2017
    expect(datetimeUtility.totalDaysInMonth(new Date(2017, 0, 1))).toBe(31);
  });
});

describe('getSundays', () => {
  it('returns array of dates representing all Sundays of the month', () => {
    // December, 2017 (it has 5 Sundays)
    const dateOfSundays = [3, 10, 17, 24, 31];
    const sundays = datetimeUtility.getSundays(new Date(2017, 11, 1));

    expect(sundays.length).toBe(5);
    sundays.forEach((sunday, index) => {
      expect(sunday.getDate()).toBe(dateOfSundays[index]);
    });
  });
});

179
describe('getTimeframeWindowFrom', () => {
180
  it('returns array of date objects upto provided length (positive number) into the future starting from provided startDate', () => {
181
    const startDate = new Date(2018, 0, 1);
182 183 184
    const mockTimeframe = [
      new Date(2018, 0, 1),
      new Date(2018, 1, 1),
185 186 187
      new Date(2018, 2, 1),
      new Date(2018, 3, 1),
      new Date(2018, 4, 31),
188
    ];
189
    const timeframe = datetimeUtility.getTimeframeWindowFrom(startDate, 5);
190

191
    expect(timeframe.length).toBe(5);
192
    timeframe.forEach((timeframeItem, index) => {
193 194 195
      expect(timeframeItem.getFullYear()).toBe(mockTimeframe[index].getFullYear());
      expect(timeframeItem.getMonth()).toBe(mockTimeframe[index].getMonth());
      expect(timeframeItem.getDate()).toBe(mockTimeframe[index].getDate());
196 197
    });
  });
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216

  it('returns array of date objects upto provided length (negative number) into the past starting from provided startDate', () => {
    const startDate = new Date(2018, 0, 1);
    const mockTimeframe = [
      new Date(2018, 0, 1),
      new Date(2017, 11, 1),
      new Date(2017, 10, 1),
      new Date(2017, 9, 1),
      new Date(2017, 8, 1),
    ];
    const timeframe = datetimeUtility.getTimeframeWindowFrom(startDate, -5);

    expect(timeframe.length).toBe(5);
    timeframe.forEach((timeframeItem, index) => {
      expect(timeframeItem.getFullYear()).toBe(mockTimeframe[index].getFullYear());
      expect(timeframeItem.getMonth()).toBe(mockTimeframe[index].getMonth());
      expect(timeframeItem.getDate()).toBe(mockTimeframe[index].getDate());
    });
  });
217
});
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234

describe('formatTime', () => {
  const expectedTimestamps = [
    [0, '00:00:00'],
    [1000, '00:00:01'],
    [42000, '00:00:42'],
    [121000, '00:02:01'],
    [10921000, '03:02:01'],
    [108000000, '30:00:00'],
  ];

  expectedTimestamps.forEach(([milliseconds, expectedTimestamp]) => {
    it(`formats ${milliseconds}ms as ${expectedTimestamp}`, () => {
      expect(datetimeUtility.formatTime(milliseconds)).toBe(expectedTimestamp);
    });
  });
});
235 236 237 238 239 240 241

describe('datefix', () => {
  describe('pad', () => {
    it('should add a 0 when length is smaller than 2', () => {
      expect(datetimeUtility.pad(2)).toEqual('02');
    });

242
    it('should not add a zero when length matches the default', () => {
243 244 245
      expect(datetimeUtility.pad(12)).toEqual('12');
    });

246
    it('should add a 0 when length is smaller than the provided', () => {
247 248 249 250 251
      expect(datetimeUtility.pad(12, 3)).toEqual('012');
    });
  });

  describe('parsePikadayDate', () => {
252
    // removed because of https://gitlab.com/gitlab-org/gitlab-foss/issues/39834
253 254 255 256 257 258 259 260
  });

  describe('pikadayToString', () => {
    it('should format a UTC date into yyyy-mm-dd format', () => {
      expect(datetimeUtility.pikadayToString(new Date('2020-01-29:00:00'))).toEqual('2020-01-29');
    });
  });
});
Kushal Pandya's avatar
Kushal Pandya committed
261 262 263 264 265 266 267

describe('prettyTime methods', () => {
  const assertTimeUnits = (obj, minutes, hours, days, weeks) => {
    expect(obj.minutes).toBe(minutes);
    expect(obj.hours).toBe(hours);
    expect(obj.days).toBe(days);
    expect(obj.weeks).toBe(weeks);
268
  };
Kushal Pandya's avatar
Kushal Pandya committed
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337

  describe('parseSeconds', () => {
    it('should correctly parse a negative value', () => {
      const zeroSeconds = datetimeUtility.parseSeconds(-1000);

      assertTimeUnits(zeroSeconds, 16, 0, 0, 0);
    });

    it('should correctly parse a zero value', () => {
      const zeroSeconds = datetimeUtility.parseSeconds(0);

      assertTimeUnits(zeroSeconds, 0, 0, 0, 0);
    });

    it('should correctly parse a small non-zero second values', () => {
      const subOneMinute = datetimeUtility.parseSeconds(10);
      const aboveOneMinute = datetimeUtility.parseSeconds(100);
      const manyMinutes = datetimeUtility.parseSeconds(1000);

      assertTimeUnits(subOneMinute, 0, 0, 0, 0);
      assertTimeUnits(aboveOneMinute, 1, 0, 0, 0);
      assertTimeUnits(manyMinutes, 16, 0, 0, 0);
    });

    it('should correctly parse large second values', () => {
      const aboveOneHour = datetimeUtility.parseSeconds(4800);
      const aboveOneDay = datetimeUtility.parseSeconds(110000);
      const aboveOneWeek = datetimeUtility.parseSeconds(25000000);

      assertTimeUnits(aboveOneHour, 20, 1, 0, 0);
      assertTimeUnits(aboveOneDay, 33, 6, 3, 0);
      assertTimeUnits(aboveOneWeek, 26, 0, 3, 173);
    });

    it('should correctly accept a custom param for hoursPerDay', () => {
      const config = { hoursPerDay: 24 };

      const aboveOneHour = datetimeUtility.parseSeconds(4800, config);
      const aboveOneDay = datetimeUtility.parseSeconds(110000, config);
      const aboveOneWeek = datetimeUtility.parseSeconds(25000000, config);

      assertTimeUnits(aboveOneHour, 20, 1, 0, 0);
      assertTimeUnits(aboveOneDay, 33, 6, 1, 0);
      assertTimeUnits(aboveOneWeek, 26, 8, 4, 57);
    });

    it('should correctly accept a custom param for daysPerWeek', () => {
      const config = { daysPerWeek: 7 };

      const aboveOneHour = datetimeUtility.parseSeconds(4800, config);
      const aboveOneDay = datetimeUtility.parseSeconds(110000, config);
      const aboveOneWeek = datetimeUtility.parseSeconds(25000000, config);

      assertTimeUnits(aboveOneHour, 20, 1, 0, 0);
      assertTimeUnits(aboveOneDay, 33, 6, 3, 0);
      assertTimeUnits(aboveOneWeek, 26, 0, 0, 124);
    });

    it('should correctly accept custom params for daysPerWeek and hoursPerDay', () => {
      const config = { daysPerWeek: 55, hoursPerDay: 14 };

      const aboveOneHour = datetimeUtility.parseSeconds(4800, config);
      const aboveOneDay = datetimeUtility.parseSeconds(110000, config);
      const aboveOneWeek = datetimeUtility.parseSeconds(25000000, config);

      assertTimeUnits(aboveOneHour, 20, 1, 0, 0);
      assertTimeUnits(aboveOneDay, 33, 2, 2, 0);
      assertTimeUnits(aboveOneWeek, 26, 0, 1, 9);
    });
338 339 340 341 342 343

    it('should correctly parse values when limitedToHours is true', () => {
      const twoDays = datetimeUtility.parseSeconds(173000, { limitToHours: true });

      assertTimeUnits(twoDays, 3, 48, 0, 0);
    });
Kushal Pandya's avatar
Kushal Pandya committed
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
  });

  describe('stringifyTime', () => {
    it('should stringify values with all non-zero units', () => {
      const timeObject = {
        weeks: 1,
        days: 4,
        hours: 7,
        minutes: 20,
      };

      const timeString = datetimeUtility.stringifyTime(timeObject);

      expect(timeString).toBe('1w 4d 7h 20m');
    });

    it('should stringify values with some non-zero units', () => {
      const timeObject = {
        weeks: 0,
        days: 4,
        hours: 0,
        minutes: 20,
      };

      const timeString = datetimeUtility.stringifyTime(timeObject);

      expect(timeString).toBe('4d 20m');
    });

    it('should stringify values with no non-zero units', () => {
      const timeObject = {
        weeks: 0,
        days: 0,
        hours: 0,
        minutes: 0,
      };

      const timeString = datetimeUtility.stringifyTime(timeObject);

      expect(timeString).toBe('0m');
384 385 386 387 388 389
    });

    it('should return non-condensed representation of time object', () => {
      const timeObject = { weeks: 1, days: 0, hours: 1, minutes: 0 };

      expect(datetimeUtility.stringifyTime(timeObject, true)).toEqual('1 week 1 hour');
Kushal Pandya's avatar
Kushal Pandya committed
390 391 392
    });
  });
});
393 394 395

describe('calculateRemainingMilliseconds', () => {
  beforeEach(() => {
396
    jest.spyOn(Date, 'now').mockImplementation(() => new Date('2063-04-04T00:42:00Z').getTime());
397 398 399 400 401 402 403 404 405 406 407 408 409 410
  });

  it('calculates the remaining time for a given end date', () => {
    const milliseconds = datetimeUtility.calculateRemainingMilliseconds('2063-04-04T01:44:03Z');

    expect(milliseconds).toBe(3723000);
  });

  it('returns 0 if the end date has passed', () => {
    const milliseconds = datetimeUtility.calculateRemainingMilliseconds('2063-04-03T00:00:00Z');

    expect(milliseconds).toBe(0);
  });
});
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429

describe('newDate', () => {
  it('returns new date instance from existing date instance', () => {
    const initialDate = new Date(2019, 0, 1);
    const copiedDate = datetimeUtility.newDate(initialDate);

    expect(copiedDate.getTime()).toBe(initialDate.getTime());

    initialDate.setMonth(initialDate.getMonth() + 1);

    expect(copiedDate.getTime()).not.toBe(initialDate.getTime());
  });

  it('returns date instance when provided date param is not of type date or is undefined', () => {
    const initialDate = datetimeUtility.newDate();

    expect(initialDate instanceof Date).toBe(true);
  });
});
430 431

describe('getDateInPast', () => {
432
  const date = new Date('2019-07-16T00:00:00.000Z');
433 434
  const daysInPast = 90;

435 436
  it('returns the correct date in the past', () => {
    const dateInPast = datetimeUtility.getDateInPast(date, daysInPast);
437 438 439
    const expectedDateInPast = new Date('2019-04-17T00:00:00.000Z');

    expect(dateInPast).toStrictEqual(expectedDateInPast);
440
  });
441 442 443

  it('does not modifiy the original date', () => {
    datetimeUtility.getDateInPast(date, daysInPast);
444
    expect(date).toStrictEqual(new Date('2019-07-16T00:00:00.000Z'));
445
  });
446
});
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477

describe('getDatesInRange', () => {
  it('returns an empty array if 1st or 2nd argument is not a Date object', () => {
    const d1 = new Date('2019-01-01');
    const d2 = 90;
    const range = datetimeUtility.getDatesInRange(d1, d2);

    expect(range).toEqual([]);
  });

  it('returns a range of dates between two given dates', () => {
    const d1 = new Date('2019-01-01');
    const d2 = new Date('2019-01-31');

    const range = datetimeUtility.getDatesInRange(d1, d2);

    expect(range.length).toEqual(31);
  });

  it('applies mapper function if provided fro each item in range', () => {
    const d1 = new Date('2019-01-01');
    const d2 = new Date('2019-01-31');
    const formatter = date => date.getDate();

    const range = datetimeUtility.getDatesInRange(d1, d2, formatter);

    range.forEach((formattedItem, index) => {
      expect(formattedItem).toEqual(index + 1);
    });
  });
});
478 479 480 481 482 483 484 485

describe('secondsToMilliseconds', () => {
  it('converts seconds to milliseconds correctly', () => {
    expect(datetimeUtility.secondsToMilliseconds(0)).toBe(0);
    expect(datetimeUtility.secondsToMilliseconds(60)).toBe(60000);
    expect(datetimeUtility.secondsToMilliseconds(123)).toBe(123000);
  });
});
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509

describe('dayAfter', () => {
  const date = new Date('2019-07-16T00:00:00.000Z');

  it('returns the following date', () => {
    const nextDay = datetimeUtility.dayAfter(date);
    const expectedNextDate = new Date('2019-07-17T00:00:00.000Z');

    expect(nextDay).toStrictEqual(expectedNextDate);
  });

  it('does not modifiy the original date', () => {
    datetimeUtility.dayAfter(date);
    expect(date).toStrictEqual(new Date('2019-07-16T00:00:00.000Z'));
  });
});

describe('secondsToDays', () => {
  it('converts seconds to days correctly', () => {
    expect(datetimeUtility.secondsToDays(0)).toBe(0);
    expect(datetimeUtility.secondsToDays(90000)).toBe(1);
    expect(datetimeUtility.secondsToDays(270000)).toBe(3);
  });
});