GUI - Angular:: Example unit test for custom filter.
Change-Id: I82863bebe2f9e89097f2d2cedcc866cb884e304d
Showing
2 changed files
with
67 additions
and
0 deletions
| 1 | +// ch09-01-time-ago.js | ||
| 2 | + | ||
| 3 | +angular.module('filterApp', []) | ||
| 4 | + .filter('timeAgo', [function () { | ||
| 5 | + var _m = 1000 * 60, | ||
| 6 | + _h = _m * 60, | ||
| 7 | + _d = _h * 24, | ||
| 8 | + _mon = _d * 30; | ||
| 9 | + | ||
| 10 | + return function (ts, ignoreSecs) { | ||
| 11 | + var showSecs = !ignoreSecs, | ||
| 12 | + now = new Date().getTime(), | ||
| 13 | + diff = now - ts; | ||
| 14 | + | ||
| 15 | + if (diff < _m && showSecs) { | ||
| 16 | + return 'seconds ago'; | ||
| 17 | + } else if (diff < _h) { | ||
| 18 | + return 'minutes ago'; | ||
| 19 | + } else if (diff < _d) { | ||
| 20 | + return 'hours ago'; | ||
| 21 | + } else if (diff < _mon) { | ||
| 22 | + return 'days ago'; | ||
| 23 | + } else { | ||
| 24 | + return 'months ago'; | ||
| 25 | + } | ||
| 26 | + } | ||
| 27 | + }]); |
| 1 | +// ch09-01-time-agoSpec.js | ||
| 2 | + | ||
| 3 | +describe('timeAgo Filter', function () { | ||
| 4 | + beforeEach(module('filterApp')); | ||
| 5 | + | ||
| 6 | + var filter; | ||
| 7 | + beforeEach(inject(function (timeAgoFilter) { | ||
| 8 | + filter = timeAgoFilter; | ||
| 9 | + })); | ||
| 10 | + | ||
| 11 | + it('should respond based on timestamp', function() { | ||
| 12 | + // The presence of new Date().getTime() makes it slightly | ||
| 13 | + // hard to unit test deterministically. | ||
| 14 | + // Ideally, we would inject a dateProvider into the timeAgo | ||
| 15 | + // filter, but we are trying to keep it simple for now. | ||
| 16 | + // So, we assume that our tests are fast enough to execute | ||
| 17 | + // in mere milliseconds. | ||
| 18 | + | ||
| 19 | + var t = new Date().getTime(); | ||
| 20 | + t -= 10000; | ||
| 21 | + expect(filter(t)).toEqual('seconds ago'); | ||
| 22 | + expect(filter(t, true)).toEqual('minutes ago'); | ||
| 23 | + | ||
| 24 | + var fmin = t - 1000 * 60; | ||
| 25 | + expect(filter(fmin)).toEqual('minutes ago'); | ||
| 26 | + expect(filter(fmin, true)).toEqual('minutes ago'); | ||
| 27 | + | ||
| 28 | + var fhour = t - 1000 * 60 * 68; | ||
| 29 | + expect(filter(fhour)).toEqual('hours ago'); | ||
| 30 | + expect(filter(fhour, true)).toEqual('hours ago'); | ||
| 31 | + | ||
| 32 | + var fday = t - 1000 * 60 * 60 * 26; | ||
| 33 | + expect(filter(fday)).toEqual('days ago'); | ||
| 34 | + expect(filter(fday, true)).toEqual('days ago'); | ||
| 35 | + | ||
| 36 | + var fmon = t - 1000 * 60 * 60 * 24 * 34; | ||
| 37 | + expect(filter(fmon)).toEqual('months ago'); | ||
| 38 | + expect(filter(fmon, true)).toEqual('months ago'); | ||
| 39 | + }); | ||
| 40 | +}); |
-
Please register or login to post a comment