【问题标题】:Test angular controllers with Jasmine - module issue使用 Jasmine 测试角度控制器 - 模块问题
【发布时间】:2015-02-15 03:31:50
【问题描述】:

我决定学习如何使用 Jasmine 测试我的 Angular 代码。当我不使用特定的依赖项时一切正常,但如果有一些依赖项我会遇到问题。例如我们有 controllers.js:

angular.module('myApp', ['jmdobry.angular-cache'])

.controller('MyCtrl', ['$scope', '$http', function($scope, $http) {
    $scope.myName = "Wojtek";
    /...
}]);

现在我想测试一下:

describe('myApp', function() {
var scope,
controller;

beforeEach(angular.mock.module('myApp'));

describe('MyCtrl', function() {
    beforeEach(inject(function ($rootScope, $controller) {
        scope = $rootScope.$new();
        controller = $controller('MyCtrl', {
            '$scope': scope
        });
    }));
    it('sets proper name', function () {
        expect(scope.myName).toBe("Wojtek");
    });
  });
});

我的问题是 - 如何模拟 'jmdobry.angular-cache' 依赖项?

【问题讨论】:

  • 您希望为缓存模拟哪些功能?从我阅读的文档看来,您似乎必须配置缓存,并且由于您的测试不会进行任何配置,因此它不应该做任何事情,对吗?
  • 在当前测试中我不需要该缓存的功能,我只想运行示例测试,所以我只需要正确配置它,因为现在有输出:错误:[$injector :modulerr]...

标签: javascript angularjs dependencies jasmine


【解决方案1】:

由于您在测试中不需要该模块的实际模拟功能,您可以执行以下操作:

describe('myApp', function () {
  var scope,
    controller;

  beforeEach(angular.mock.module('jmdobry.angular-cache', [])); // just create a module that does nothing

  beforeEach(angular.mock.module('myApp'));

  describe('MyCtrl', function () {
    beforeEach(inject(function ($rootScope, $controller) {
      scope = $rootScope.$new();
      controller = $controller('MyCtrl', {
        '$scope': scope
      });
    }));
    it('sets proper name', function () {
      expect(scope.myName).toBe("Wojtek");
    });
  });
});

【讨论】:

  • 非常感谢 :) 我遇到了一些其他问题,但最后我设法做到了。再次感谢!
猜你喜欢
  • 2017-02-24
  • 1970-01-01
  • 1970-01-01
  • 2016-10-10
  • 2016-12-22
  • 1970-01-01
  • 1970-01-01
  • 2016-09-13
  • 1970-01-01
相关资源
最近更新 更多