2011-08-16 67 views
7

我有以下代碼:如何用JsTestDriver測試AngularJS控制器?

function TestStats($xhr) { 
    $xhr(
      'GET', 
      '/test-dashboard/get-projects.json', 
      angular.bind(this, function(code, response) { 
       this.projects = response.projects; 
       this.projects.splice(0, 0, undefined); 
      })); 

    this.$watch('project', angular.bind(this, function() { 
     this.testClassStats = undefined; 

     if (this.project) { 
      $xhr(
        'GET', 
        '/test-dashboard/get-test-stats.json?project=' + this.project, 
        angular.bind(this, function(code, response) { 
         this.testClassStats = response.testClassStats; 
        })); 
     } 
    })); 
}; 

TestStats.prototype.greet = function(name) { 
    return "Hello " + name + "!"; 
}; 

TestStats.$inject = ['$xhr']; 

和以下測試:

TestDashboardUnitTest = TestCase("TestDashboardUnitTest"); 

TestDashboardUnitTest.prototype.testAoeu = function() { 
    var xhrStub = function(method, url, callback) { 
    }; 
    var testStats = new TestStats(xhrStub); 
    assertEquals("Hello World!", testStats.greet("Aoeu")); 
}; 

和以下配置:

server: http://localhost:9876 

load: 
    - http://code.jquery.com/jquery-1.6.2.min.js 
    - http://code.angularjs.org/angular-0.9.17.min.js 
    - web/*.js 
    - test/*.js 

當運行測試,JsTestDriver輸出:

Total 1 tests (Passed: 0; Fails: 0; Errors: 1) (0.00 ms) 
    Chrome 13.0.782.112 Linux: Run 1 tests (Passed: 0; Fails: 0; Errors 1) (0.00 ms) 
    TestDashboardUnitTest.testAoeu error (0.00 ms): TypeError: Object #<TestStats> has no method '$watch' 
     TypeError: Object #<TestStats> has no method '$watch' 
      at new TestStats (http://127.0.0.1:9876/test/web/test-dashboard.js:13:10) 
      at [object Object].testAoeu (http://127.0.0.1:9876/test/test/test-dashboard-unit-test.js:9:21) 

Tests failed: Tests failed. See log for details. 

我需要做些什麼來解決這個問題?

回答

5

http://docs.angularjs.org/#!/tutorial/step_05

scope = angular.scope(); 
$browser = scope.$service('$browser'); 

$browser.xhr.expectGET('phones/phones.json') 
    .respond([{name: 'Nexus S'}, 
       {name: 'Motorola DROID'}]); 
ctrl = scope.$new(PhoneListCtrl); 

不要做平常的事情,並通過在嘲笑。相反,讓注射系統完成這項工作。

此外,請務必在jsTestDriver.conf文件中加載angular-mocks.js。

+1

是的,這是正確的方法來測試控制器,它使用範圍的api像'$ watch'。 – Vojta

+0

「另外,一定要在jsTestDriver.conf文件中加載angular-mocks.js。」你可以擴展這個嗎?這個.conf文件在哪裏? – cdmckay

1

我不知道角做什麼,但在我看來,你的問題是在這個代碼塊:

this.$watch('project', angular.bind(this, function() { 
    // snip 
})); 

當你調用this.$watch方法,您呼叫的對象的方法類的實例TestStats - 在您提供的第一個代碼塊中描述的類。我沒有看到任何地方有一種叫做$watch的方法,也許你需要一些其他的對象引用,而不是this