使用 Karma (Jasmine) 测试 AngularJS 工厂

时间:2023-04-30
本文介绍了使用 Karma (Jasmine) 测试 AngularJS 工厂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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

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

我无法将我的工厂注入到 OfficerValidationService 变量中.

I am unable to inject my factory to OfficerValidationService variable.

我做错了什么?

注意:文件加载正确

工厂:

'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)

推荐答案

需要调用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();
    });

  });
}());

这篇关于使用 Karma (Jasmine) 测试 AngularJS 工厂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:使用 Jasmine 在 JavaScript 中存根 WebSocket 下一篇:使用 Jasmine 监视函数中的变量

相关文章

最新文章