【问题标题】:Error testing Angular services with Jasmine/Chutzpah使用 Jasmine/Chutzpah 测试 Angular 服务时出错
【发布时间】:2017-08-04 21:20:06
【问题描述】:

我正在尝试使用 Jasmine 测试我的 AngularJs 服务,但我不断收到各种错误。 所以我尝试创建一个非常基本的 Sum 服务来测试它,并且错误不断出现。

这是我要测试的 AngularJS 服务:

   angular.module('base', [])
   .service('operacoes', [function () {
      this.somar = function (n1,n2) {
          return n1 + n2;
      };
   }]);

我的测试:

/// <reference path="../../Scripts/angularjs/angular.min.js" />
/// <reference path="../../Scripts/angularjs/angular-mocks.js" />
/// <reference path="../../ServicoBase.js" />
describe("Testing Services", function () {
    var operacoesObj;

    beforeEach(angular.module('base'));

    beforeEach(inject(function (operacoes) {
        operacoesObj = operacoes;
    }));

    it('deve ter inicializado', function () {
        expect(operacoesObj).toBeDefined();
    });

    it('deve conseguir somar 2 números', function () {
        expect(operacoesObj.somar(5, 1)).to.equal(6);
    });
});

尝试运行此测试会返回以下错误:

  • TypeError:对象不支持属性或方法“调用”
  • [$injector:unpr] http://errors.angularjs.org/1.4.4/$injector/unpr?p0=operacoesProvider%20%3C-%20operacoes
  • 预计未定义。

我尝试过其他 Jasmine 版本,例如 2.4.1(现在在 2.5.2 上运行)。

【问题讨论】:

    标签: javascript angularjs unit-testing jasmine chutzpah


    【解决方案1】:

    测试服务与测试控制器不同。您应该使用$injector.get() 返回服务实例。我将您的测试代码更改为以下内容并且测试通过了:

    describe("Testing Services", function () {
        var svc;
    
        beforeEach(function() {
            angular.mock.module('base')
    
            inject(function($injector) {
                svc = $injector.get('operacoes');
            })
        });    
    
        it('deve ter inicializado', function () {
            expect(svc).toBeDefined();
        });
    
        it('deve conseguir somar 2 números', function () {
            expect(svc.somar(5, 1)).toEqual(6);
        });
    });
    

    查看单元测试服务here的角度文档。

    此外,实际上并没有必要通过测试来检查服务是否已定义。您将知道服务是否未定义,因为如果未定义,您的所有其他单元测试都会失败。

    【讨论】:

    • 做到了。非常感谢!
    【解决方案2】:

    试试这个:

    describe("Testing Services", function() {
      beforeEach(module('base'));
    
      it('deve ter inicializado', inject(function(operacoes) {
        expect(operacoes).toBeDefined();
      }));
    
    
      it('deve conseguir somar 2 números', inject(function(operacoes) {
    
        expect(operacoes.somar(5, 1)).toEqual(6);
    
      }))
    
    });
    

    【讨论】:

    • 同样的错误,我的模块被命名为'base'而不是'app'。正如@TehBeardedOne 所说,问题在于注射。
    猜你喜欢
    • 2013-08-25
    • 1970-01-01
    • 1970-01-01
    • 2017-09-15
    • 2016-05-28
    • 2016-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多