2014-06-05 33 views
0

所以我有一個簡單的函數:有人可以幫助解釋如何用Jasmine測試這個AngularJS嗎?

wpApp = angular.module('wpApp', ['ngRoute']); 

wpApp.controller("ctrlr", function($scope) { 
    $scope.message = 'This is the page'; 
}); 

而且我想它使用茉莉用下面的規格來進行測試:當實際值來

describe("A suite", function() { 
    var scope; 
    beforeEach(inject(function($rootScope, $controller) { 
     scope = $rootScope.$new(); 
     $controller("controller", { 
      $scope: scope 
     }); 
    })); 

    it("should have the default message", function() { 
     return expect(scope.message).toBe('This is the page'); 
    }); 
}); 

但是,它不工作,沒有定義。

我對AngularJS以及注射的想法都比較陌生。我一直在瀏覽StackOverflow,在文檔和教程中,我似乎無法弄清楚我做錯了什麼。

希望它是一個小東西。有人能幫我看看我需要改變我的規格嗎?

回答

4

你需要加載模塊:

beforeEach(module('wpApp')); 

然後,你需要加載正確的控制器:

$controller("ctrlr", { 
    $scope: scope 
}); 

完整代碼:

describe("A suite", function() { 
    var scope; 

    beforeEach(module('wpApp')); 

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

    it("should have the default message", function() { 
    return expect(scope.message).toBe('This is the page'); 
    }); 
}); 

或者:

describe("A suite", function() { 

    var $scope; 

    beforeEach(function() { 

    module('wpApp'); 

    inject(function($rootScope, $controller) { 

     $scope = $rootScope.$new(); 

     $controller("ctrlr", { 
     $scope: $scope 
     }); 
    }) 
    }); 

    it("should have the default message", function() { 
    return expect($scope.message).toBe('This is the page'); 
    }); 
}); 
+0

謝謝!你能否快速解釋一下注射功能到底在做什麼?我明白這個想法是「注入」了函數的參數,但爲什麼給它兩個參數$ rootScope和$ controller?你總是隻給那兩個嗎? – elykl33t

+0

不客氣:)這是一個解釋,但如果您仍然有問題,請讓我知道:https://docs.angularjs.org/api/ngMock/function/angular.mock.inject – tasseKATT

相關問題