How to Jasmine test code within angular module run block
Asked Answered
P

1

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
Prado answered 25/7, 2014 at 5:22 Comment(2)
"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.Eleanoraeleanore
Managed to figure it out.Prado
P
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();
  });
});
Prado answered 25/7, 2014 at 6:19 Comment(1)
Nice post about testing config and run blocks in AngularJS: blog.andre-eife.com/2015/02/10/test-run-and-config-blocks.htmlMonostylous

© 2022 - 2024 — McMap. All rights reserved.