Permalink
Browse files

Add a couple of tests for the timer

  • Loading branch information...
lucapette committed Mar 12, 2017
1 parent a1f0a98 commit f2e5234ba063b62de71428c132b54b54463848d0
Showing with 71 additions and 7 deletions.
  1. +37 −3 src/timer.js
  2. +34 −4 src/timer.test.js
View
@@ -1,10 +1,44 @@
//@flow
+type CallbackType = 'tick' | 'done';
+type Callback = (number | void) => void;
+
export default class Timer {
- minutes: number;
+ seconds: number;
+ callbacks: Map<CallbackType, Callback>;
- constructor(minutes: number = 25) {
- this.minutes = minutes;
+ constructor(seconds: number = 25 * 60) {
+ this.seconds = seconds;
+ this.callbacks = new Map();
}
+ start() {
+ let start = Date.now();
+ let elapsed = 0;
+ let lastElapsed = 0;
+
+ setInterval(() => {
+ elapsed = Math.floor((Date.now() - start) / 1000);
+
+ if (elapsed != lastElapsed) {
+ lastElapsed = elapsed;
+ let callback = this.callbacks.get('tick');
+ if (callback) {
+ callback(Math.floor((elapsed/this.seconds) * 100));
+ }
+ }
+
+ if (elapsed >= this.seconds) {
+ let callback = this.callbacks.get('done');
+ if (callback) {
+ callback();
+ }
+ return
+ }
+ }, 1000);
+ }
+
+ on(type : CallbackType, callback : Callback) {
+ this.callbacks.set(type, callback);
+ }
}
View
@@ -1,7 +1,37 @@
-//@flow
import Timer from './timer'
-test('it has defaults', () => {
- var timer = new Timer();
- expect(timer.minutes).toBe(25);
+jest.useFakeTimers();
+
+beforeEach(() => {
+ Date.now = jest.fn().
+ mockReturnValueOnce(new Date(2015, 10, 21, 7, 28, 0)).
+ mockReturnValue(new Date(2015, 10, 21, 7, 28, 1));
+});
+
+test('it ticks correctly', () => {
+ var timer = new Timer(1);
+
+ const tick = jest.fn();
+
+ timer.on('tick', tick);
+
+ timer.start();
+
+ jest.runTimersToTime(1000);
+
+ expect(tick.mock.calls.length).toBe(1);
+});
+
+test('it finishes correctly', () => {
+ var timer = new Timer(1);
+
+ const done = jest.fn();
+
+ timer.on('done', done);
+
+ timer.start();
+
+ jest.runTimersToTime(1000);
+
+ expect(done.mock.calls.length).toBe(1);
});

0 comments on commit f2e5234

Please sign in to comment.