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
2
  • 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 ;) 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. Commented Jul 25, 2014 at 5:42
  • Managed to figure it out. Commented Jul 25, 2014 at 6:19

1 Answer 1

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();
  });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Nice post about testing config and run blocks in AngularJS: blog.andre-eife.com/2015/02/10/test-run-and-config-blocks.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.