使用茉莉花测试角度控制器 - 模块问题

Test angular controllers with Jasmine - module issue

本文关键字:控制器 模块 问题 茉莉花 测试      更新时间:2023-09-26

我决定学习如何用Jasmine测试我的角度代码。当我不使用特定的依赖项时,一切都可以正常工作,但如果有一些依赖项,我就有问题。例如,我们有控制器.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"依赖关系?

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

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");
    });
  });
});