一尘不染

使用Karma(Jasmine)测试AngularJS工厂

angularjs

我正在努力使用Karma + Jasmine测试AngularJS工厂。

我无法将工厂注入OfficerValidationService变量。

我究竟做错了什么?

注意:文件已正确加载

厂:

'use strict';

angular.module('darthvader').factory('OfficerValidationService', [function(){

  var OfficerValidationService = {};

  OfficerValidationService.something = function() {
    return true;
  };

  return OfficerValidationService;

}]);

码:

'use strict';

(function() {
  describe('OfficerValidationService Spec', function() {

    var OfficerValidationService;

    beforeEach(function() {
      angular.module('darthvader');
    });

    beforeEach(module('darthvader', function($provide) {
      $provide.value('OfficerValidationService', OfficerValidationService);
    }));

    it('is very true', inject(function(OfficerValidationService){
      alert('=====' + OfficerValidationService + '=====');
      var output = OfficerValidationService.something();
      expect(output).toBeTruthy();
    }));

  });
}());

输出:

Running "karma:unit" (karma) task
INFO [karma]: Karma v0.12.17 server started at http://localhost:9876/
INFO [launcher]: Starting browser PhantomJS
INFO [PhantomJS 1.9.7 (Mac OS X)]: Connected on socket yc_qTseOCArRtZLAXSTZ with id 97647403
ALERT: '=====undefined====='
PhantomJS 1.9.7 (Mac OS X) OfficerValidationService Spec is very true FAILED
    TypeError: 'undefined' is not an object (evaluating 'OfficerValidationService.something')
        at /Users/chuck/Desktop/sandbox/dashboard.darthvader/test/karma/unit/services/officerValidationService.js:25
        at invoke (/Users/chuck/Desktop/sandbox/dashboard.darthvader/public/lib/angular/angular.js:3917)
        at workFn (/Users/chuck/Desktop/sandbox/dashboard.darthvader/public/lib/angular-mocks/angular-mocks.js:2155)
    undefined
PhantomJS 1.9.7 (Mac OS X): Executed 28 of 28 (1 FAILED) (0.102 secs / 0.131 secs)

阅读 271

收藏
2020-07-04

共1个答案

一尘不染

您需要致电angular.injector

'use strict';

(function() {
  describe('OfficerValidationService Spec', function() {

    var OfficerValidationService;

    beforeEach(function() {
      angular.module('darthvader');
    });

    beforeEach(inject(function() {
      var $injector = angular.injector(['darthvader']);
      OfficerValidationService = $injector.get('OfficerValidationService');
    }));

    it('is very true', function(){
      var output = OfficerValidationService.something();
      expect(output).toBeTruthy();
    });

  });
}());
2020-07-04