Mock Angular JS控制器Jasmine

时间:2015-12-09 12:17:43

标签: javascript angularjs jasmine tdd

我是角度js的新手..刚刚建立了一个样本控制器..现在想要对它进行单元测试..不确定如何在茉莉花中嘲笑它..

TestApp.js

var TestApp = angular.module('TestApp');  
TestApp.controller('TestCtrl', function($scope) {
    $scope.test = "test";
    });
})();

TestApp_Spec.js

var scope, ctrl;

//you need to inject dependencies first
beforeEach(inject(function($rootScope) {
    $scope = $rootScope.$new();        
}));

it('test value should be test', inject(function($controller) {
    ctrl = $controller('TestCtrl', {
        scope: $scope
    });
    expect(scope.test).toBe("test");
}));

我正在使用独立版本的jasmine,并在sepc_runner.html中包含angular.min.js,angular.mocks.js,TestApp.js和TestApp_Spec.js

测试结果没有显示出来..

在编写正确的测试用例时需要帮助..

1 个答案:

答案 0 :(得分:0)

您的代码中有一些修复,例如您未在测试套件中插入模块,因此jasmine无法找到controller

您尚未在模块中传递第二个参数,即数组作为依赖项,即angular.module('TestApp',[]);

Here is the working plunker.

<强> app.js

(function(){
var TestApp = angular.module('TestApp',[]);  
TestApp.controller('TestCtrl',["$scope",function(scope) {
        alert(scope)
        scope.test = "test";
    }]);
})();

测试套装

var scope, ctrl;
describe('MyApp', function() {
  beforeEach(module('TestApp'));
  //you need to inject dependencies first

  beforeEach(inject(function($controller,$rootScope) {
     scope = $rootScope.$new(); 
     $controller('TestCtrl', {
          '$scope': scope
      });       
  }));

  it('test value should be test',function(){
    expect(scope.test).toBe("test");
  });
});