Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test an IntervalObservable

In my Angular app, I make use of an IntervalObservable in order to periodically perform some actions (in my case every 5 minutes):

IntervalObservable.create(300000) // 5 minutes
  .subscribe(() => {
    this.someMethodReturningObs().subscribe((data) => {
      this.myData = data;
    });
  });

how I can unit test it?

like image 858
Francesco Borzi Avatar asked Dec 11 '25 18:12

Francesco Borzi


1 Answers

Update:

To verify this.myData for every 5 mins.

it("should test data for 5min interval", fakeAsync(() => { 
tick(300000);
expect(myData).toBe(testValue);
}))

Old Answer

Jasmine.clock can be used for your puposes. Check the below example from doc

beforeEach(function() {
    timerCallback = jasmine.createSpy("timerCallback");
    jasmine.clock().install();
  });

Be sure to uninstall the clock after you are done to restore the original timer functions.

afterEach(function() {
    jasmine.clock().uninstall();
  });

Calls to any registered callback are triggered when the clock is ticked forward via the jasmine.clock().tick function, which takes a number of milliseconds.

it("causes a timeout to be called synchronously", function() {
    setTimeout(function() {
      timerCallback();
    }, 100);

    expect(timerCallback).not.toHaveBeenCalled();

    jasmine.clock().tick(300000);

    expect(timerCallback).toHaveBeenCalled();
  });
like image 81
Karthick Manoharan Avatar answered Dec 14 '25 11:12

Karthick Manoharan