Skip to content

Instantly share code, notes, and snippets.

@stewx
Last active March 29, 2019 13:12
Show Gist options
  • Save stewx/284384b3dc83318f1a9f2be66575ccb5 to your computer and use it in GitHub Desktop.
Save stewx/284384b3dc83318f1a9f2be66575ccb5 to your computer and use it in GitHub Desktop.
Mock rxjs 5 Observable.timer for Angular unit tests with Jasmine
export function setFakeTimer(maxFrames?: number): TestScheduler {
const originalTimer = Observable.timer;
const scheduler = new TestScheduler((a, b) => expect(a).toEqual(b));
if (maxFrames) {
scheduler.maxFrames = maxFrames;
}
spyOn(Observable, 'timer').and.callFake((initialDelay: number, dueTime: number) => {
return originalTimer.call(this, initialDelay, dueTime, scheduler);
});
return scheduler;
}
// Sample code under test, to increment counter every second
let counter = 0;
Observable.timer(0, 1000).do(() => {
counter++;
}).take(3).subscribe();
// Sample test
it('should increment the counter every second', async(() => {
setFakeTimer(5000);
scheduler.schedule(() => {
expect(counter).toBe(1);
}, 0, null);
scheduler.schedule(() => {
expect(counter).toBe(2);
}, 1000, null);
scheduler.schedule(() => {
expect(counter).toBe(3);
}, 2000, null);
scheduler.flush();
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment