jasmine + angular ex 11

$timeout

by ronapelbaum

HTML

<script src="https://jasmine.github.io/2.4/lib/jasmine.js"></script>
<script src="https://jasmine.github.io/2.4/lib/jasmine-html.js"></script>
<script src="https://jasmine.github.io/2.4/lib/boot.js"></script>
<link rel="stylesheet" href="https://jasmine.github.io/2.4/lib/jasmine.css">
<script src="https://code.angularjs.org/1.4.9/angular.js"></script>
<script src="https://code.angularjs.org/1.4.9/angular-mocks.js"></script>

JavaScript

//--------------BL------------
(function() {

  function MyController($timeout) {
    this.greeting = null;
    var that = this;
    this.greet = function(greeting) {
      $timeout(function() {
        that.greeting = greeting + ' bob';
      }, 500);
    }
  }
  angular.module('MyModule', [])
    .controller('MyController', ['$timeout', MyController]);
})();

//--------------specs------------
describe("MyController Spec", function() {
  var $controller, $timeout;
  beforeEach(module('MyModule'));

  beforeEach(inject(function(_$controller_, _$timeout_) {
    $controller = _$controller_;
    $timeout = _$timeout_;
  }));

  it("greeting should be 'Hello Bob'", function() {
    var ctrl = $controller("MyController");
    ctrl.greet('Hello');
    //not yet...    
    expect(ctrl.greeting).toBeNull();
    //flush!
    $timeout.flush();
    //now you're talking!
    expect(ctrl.greeting).toBe('Hello bob');
  });

  it("greeting should be 'Hello Bob'", function() {
    var ctrl = $controller("MyController");
    ctrl.greet('Hello');
    //not yet...
    expect(ctrl.greeting).toBeNull;
    //flush!
    $timeout.flush(499);
    //not yet...
    expect(ctrl.greeting).toBeNull;
    //flush!
    $timeout.flush(1); //now you're talking!
    expect(ctrl.greeting).toBe('Hello bob');
  });

});