簡體   English   中英

模擬角JS控制器茉莉花

[英]Mock Angular JS Controller Jasmine

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

我正在使用茉莉花的獨立版本,並且在sepc_runner.html中包含了angular.min.js,angular.mocks.js,TestApp.js和TestApp_Spec.js

測試結果未顯示。

在編寫正確的測試用例時需要幫助。

您的代碼中有一些修復程序,例如您沒有在測試服中插入模塊,因此jasmine無法找到controller

您尚未在模塊中傳遞第二個參數作為數組的依賴項,即angular.module('TestApp',[]);

這是工作中的笨蛋。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM