最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to Jasmine test code within angular module run block - Stack Overflow

programmeradmin0浏览0评论

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

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
Share Improve this question edited Jul 25, 2014 at 6:25 Andrew asked Jul 25, 2014 at 5:22 AndrewAndrew 5,7155 gold badges37 silver badges41 bronze badges 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. – Sunil D. Commented Jul 25, 2014 at 5:42
  • Managed to figure it out. – Andrew Commented Jul 25, 2014 at 6:19
Add a comment  | 

1 Answer 1

Reset to default 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();
  });
});
发布评论

评论列表(0)

  1. 暂无评论