Created
March 15, 2017 08:45
-
-
Save joshski/41821d0e16fffe27f1d5725f3fc3cd71 to your computer and use it in GitHub Desktop.
countdown-timers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const assert = require('assert') | |
const lolex = require('lolex') | |
class CountdownTimerWithSetTimeout { | |
countdownFrom(n, element) { | |
element.innerText = n | |
setTimeout(() => { | |
n-- | |
element.innerText = n | |
if (n > 0) { | |
this.countdownFrom(n, element) | |
} | |
}, 1000) | |
} | |
} | |
class CountdownTimerWithClock { | |
constructor(clock) { | |
this.clock = clock | |
} | |
countdownFrom(n, element) { | |
element.innerText = n | |
this.clock.eachSecond(() => { | |
n-- | |
if (n >= 0) { | |
element.innerText = n | |
} | |
}) | |
} | |
} | |
describe('countdown timers', function() { | |
beforeEach(function() { | |
this.element = { innerText: '' } | |
}) | |
describe(CountdownTimerWithSetTimeout.name, function() { | |
beforeEach(function() { | |
this.clock = lolex.install() | |
}) | |
afterEach(function() { | |
this.clock.uninstall() | |
}) | |
it('counts down from 3 to 0', function() { | |
new CountdownTimerWithSetTimeout().countdownFrom(3, this.element) | |
assert.equal(this.element.innerText, '3') | |
this.clock.tick(1000) | |
assert.equal(this.element.innerText, '2') | |
this.clock.tick(1000) | |
assert.equal(this.element.innerText, '1') | |
this.clock.tick(1000) | |
assert.equal(this.element.innerText, '0') | |
this.clock.tick(1000) | |
assert.equal(this.element.innerText, '0') | |
}) | |
}) | |
describe(CountdownTimerWithClock.name, function() { | |
beforeEach(function() { | |
this.clock = { | |
eachSecond(callback) { this.callback = callback }, | |
tick() { this.callback() } | |
} | |
}) | |
it('counts down from 3 to 0', function() { | |
new CountdownTimerWithClock(this.clock).countdownFrom(3, this.element) | |
assert.equal(this.element.innerText, '3') | |
this.clock.tick() | |
assert.equal(this.element.innerText, '2') | |
this.clock.tick() | |
assert.equal(this.element.innerText, '1') | |
this.clock.tick() | |
assert.equal(this.element.innerText, '0') | |
this.clock.tick() | |
assert.equal(this.element.innerText, '0') | |
}) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment