Mocking timers

One last thing we'll talk about is how to handle unit testing when your service uses either the $timer or $interval service. Calls to these services can cause a delay in executing your unit tests, and one of the things we want when executing unit tests is for them to execute as quickly as possible. This way, we get feedback as quickly as possible as we modify our code.

The AngularJS Mock library provides mock services for both of these services, allowing us to skip ahead in time so that the timeout interval passes quickly, thus allowing the test to execute as fast as possible. Both mock services provide a flush method that allows you to specify the number of milliseconds to skip ahead so that your timeout interval is triggered:

describe("polling service", function(){
  var interval;
  var service;
  var httpBackend

  beforeEach(module('application.services'));

  beforeEach(inject(function (poll_service, $interval, 
    $httpBackend) {
    service = data_service;
    interval = $interval;
    httpBackend = $httpBackend;
  }));

  it("should poll the status method after 30 seconds", function(){
    httpBackend.expectGet('/status').respond(200, [
      {id: 1, message: 'test message'},
      {id: 2, message: 'test message'}]);

    var messages = [];
    service.init().then(function(response){
      messages = response;
      expect(messages.length).toBe(2);
    });

    interval.flush(30000);

    httpBackend.flush();
  });

  afterEach(function() {
    $httpBackend.verifyNoOutstandingExpectation();
    $httpBackend.verifyNoOutstandingRequest();
  });
});

The preceding unit test provides an example of how to use the $interval mock service to skip 30 seconds ahead during our unit test, thus causing the service under test to make an HTTP request to url '/status'. As we did earlier, we add variables to the scenario to hold the $httpBackend and $interval mock services that are injected during the call to beforeEach. Then, during the scenario, we make a call to the flush method on the $interval service with a value of 30,000 milliseconds to skip 30 seconds ahead so that the timeout interval is triggered, and the HTTP request is made immediately.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.121.8