如何在 Angular 模块运行块中测试 Jasmine 代码

我想 Jasmine 测试一下是否调用了 Welcome.go.Welcome 是一个 Angular 服务.

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();
  });

这是我目前的测试:

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();
  });
});

注意:

  • welcome(小写w)是模块
  • 欢迎(大写 W)是服务

推荐答案

设法弄明白了.这是我想出的:

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();
  });
});

相关文章