12

I would like to Jasmine test that Welcome.go has been called. Welcome is an angular service.

angular.module('welcome',[])
  .run(function(Welcome) {
    Welcome.go();
  });

This is my test so far:

describe('module: welcome', function () {

  beforeEach(module('welcome'));

  var Welcome;
  beforeEach(inject(function(_Welcome_) {
    Welcome = _Welcome_;
    spyOn(Welcome, 'go');
  }));

  it('should call Welcome.go', function() {
    expect(Welcome.go).toHaveBeenCalled();
  });
});

Note:

  • welcome (lowercase w) is the module
  • Welcome (uppercase W) is the service
Andrew
  • 5,525
  • 5
  • 36
  • 40
  • 4
    "Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests." -- that's from the [Angular documentation](https://docs.angularjs.org/guide/module) ;) It's not clear what `Welcome.go()` does, but you might consider calling that from one of your app's top level controllers, which you can test as shown above. – Sunil D. Jul 25 '14 at 05:42
  • Managed to figure it out. – Andrew Jul 25 '14 at 06:19

1 Answers1

20

Managed to figure it out. Here is what I came up with:

'use strict';

describe('module: welcome', function () {

  var Welcome;

  beforeEach(function() {
    module('welcome', function($provide) {
      $provide.value('Welcome', {
        go: jasmine.createSpy('go')
      });
    });

    inject(function (_Welcome_) {
      Welcome = _Welcome_;
    })
  });


  it('should call Welcome.go on module run', function() {
    expect(Welcome.go).toHaveBeenCalled();
  });
});
Andrew
  • 5,525
  • 5
  • 36
  • 40
  • Nice post about testing config and run blocks in AngularJS: http://blog.andre-eife.com/2015/02/10/test-run-and-config-blocks.html – dbabaioff Jun 03 '15 at 09:08