Skip to content

Instantly share code, notes, and snippets.

@kubk
Created September 7, 2021 14:16
Show Gist options
  • Save kubk/412ebe01c120d957f97b82de85d901bd to your computer and use it in GitHub Desktop.
Save kubk/412ebe01c120d957f97b82de85d901bd to your computer and use it in GitHub Desktop.
Mobx test timers
import { TimeTrackerStore } from './time-tracker-store';
import { action, makeAutoObservable } from 'mobx';
class Counter {
value = 0;
intervalId?: NodeJS.Timer;
constructor() {
makeAutoObservable(this);
}
start() {
this.intervalId = setInterval(
action(() => {
this.value++;
}),
1000
);
}
stop() {
if (this.intervalId) {
clearInterval(this.intervalId);
}
}
}
describe('TimeTrackerStore', () => {
it('increments time', () => {
jest.useFakeTimers();
const counter = new Counter();
expect(counter.value).toBe(0);
counter.start();
jest.advanceTimersByTime(2500);
expect(counter.value).toBe(2);
jest.advanceTimersByTime(3000);
expect(counter.value).toBe(5);
counter.stop();
jest.advanceTimersByTime(3000);
expect(counter.value).toBe(5);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment