Testing an AngularJS factory with Karma (Jasmine)

后端 未结 2 798
孤独总比滥情好
孤独总比滥情好 2021-01-02 12:44

I\'m struggling with testing an AngularJS factory using Karma + Jasmine.

I am unable to inject my factory to OfficerValidationService variable.

相关标签:
2条回答
  • 2021-01-02 12:57

    To add to martynas' answer, here is a simplified version:

    module() is the shorthand of angular.mock.module
    inject() is the shorthand of angular.mock.inject (same as $injector)

    'use strict';
    
    (function() {
      describe('OfficerValidationService Spec', function() {
        var OfficerValidationService;
    
        beforeEach(module('darthvader'));
        beforeEach(inject(function (OfficerValidationService) {
          OfficerValidationService = OfficerValidationService;
        }));
    
         it('OfficerValidationService should exist', function() {
            expect(OfficerValidationService).toBeTruthy();
        });
    
    
      });
    }());
    
    0 讨论(0)
  • 2021-01-02 13:00

    You need to call 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();
        });
    
      });
    }());
    
    0 讨论(0)
提交回复
热议问题