blob: 21c227dac5d7295f1d6b77fc87ebbe0c41b696a3 [file] [log] [blame]
Copybara854996b2021-09-07 19:36:02 +00001// Copyright 2019 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5import {assert, expect} from 'chai';
6import {ChopsTimestamp} from './chops-timestamp.js';
7import {FORMATTER, SHORT_FORMATTER} from './chops-timestamp-helpers.js';
8import sinon from 'sinon';
9
10// The formatted date strings differ based on time zone and browser, so we can't
11// use static strings for testing. We can't stub out the format method because
12// it's native code and can't be modified. So just use the FORMATTER object.
13
14let element;
15let clock;
16
17describe('chops-timestamp', () => {
18 beforeEach(() => {
19 element = document.createElement('chops-timestamp');
20 document.body.appendChild(element);
21
22 // Set clock to the Epoch.
23 clock = sinon.useFakeTimers({
24 now: new Date(0),
25 shouldAdvanceTime: false,
26 });
27 });
28
29 afterEach(() => {
30 document.body.removeChild(element);
31 clock.restore();
32 });
33
34 it('initializes', () => {
35 assert.instanceOf(element, ChopsTimestamp);
36 });
37
38 it('changing timestamp changes date', async () => {
39 const timestamp = 1548808276;
40 element.timestamp = String(timestamp);
41
42 await element.updateComplete;
43
44 assert.include(element.shadowRoot.textContent,
45 FORMATTER.format(new Date(timestamp * 1000)));
46 });
47
48 it('parses ISO dates', async () => {
49 const timestamp = '2016-11-11';
50 element.timestamp = timestamp;
51
52 await element.updateComplete;
53
54 assert.include(element.shadowRoot.textContent,
55 FORMATTER.format(new Date(timestamp)));
56 });
57
58 it('invalid timestamp format', () => {
59 expect(() => {
60 element._parseTimestamp('random string');
61 }).to.throw('Timestamp is in an invalid format.');
62 });
63
64 it('short time renders shorter time', async () => {
65 element.short = true;
66 element.timestamp = '5';
67
68 await element.updateComplete;
69
70 assert.include(element.shadowRoot.textContent,
71 `just now`);
72
73 element.timestamp = '60';
74
75 await element.updateComplete;
76
77 assert.include(element.shadowRoot.textContent,
78 `a minute from now`);
79
80 const timestamp = 1548808276;
81 element.timestamp = String(timestamp);
82
83 await element.updateComplete;
84
85 assert.include(element.shadowRoot.textContent,
86 SHORT_FORMATTER.format(timestamp * 1000));
87 });
88});