2014-08-30 50 views
4

我有一個控制器我與Ember CLI測試的特性「transitionToRoute」,但控制器的承諾不會解決,因爲控制器的transitionToRoute方法返回null灰燼CLI控制器測試:遺漏的類型錯誤:無法讀取空

Uncaught TypeError: Cannot read property 'transitionToRoute' of null

login.coffee

success: (response) -> 
    # ... 

    attemptedTransition = @get("attemptedTransition") 
    if attemptedTransition 
     attemptedTransition.retry() 
     @set "attemptedTransition", null 
    else 
     @transitionToRoute "dashboard" 

login-test.coffee

`import {test, moduleFor} from "ember-qunit"` 

moduleFor "controller:login", "LoginController", { 
} 

# Replace this with your real tests. 
test "it exists", -> 
    controller = @subject() 
    ok controller 

### 
    Test whether the authentication token is passed back in JSON response, with `token` 
### 
test "obtains authentication token", -> 
    expect 2 
    workingLogin = { 
     username: "[email protected]", 
     password: "pass" 
    } 
    controller = @subject() 
    Ember.run(-> 
     controller.setProperties({ 
      username: "[email protected]", 
      password: "pass" 
     }) 
     controller.login().then(-> 
      token = controller.get("token") 
      ok(controller.get("token") isnt null) 
      equal(controller.get("token").length, 64) 
     ) 
    ) 

當行@transitionToRoute("dashboard")被移除時,測試通過;否則,測試失敗。

如何解決此錯誤,同時仍然保持我的控制器邏輯?

+0

'transitionToRoute'不返回null,它*爲* null。我猜想這不是你所懷疑的。我對coffeescript不感興趣,無法讓我擔心它:) – 2014-08-31 02:47:20

+0

如果您找到了解決方案,請將其作爲答案發布,因爲我面臨類似的問題。 – Mawaheb 2014-12-18 14:23:04

回答

2

變通方法:繞過transitionToRoute如果targetnull。例如:

if (this.get('target')) { 
    this.transitionToRoute("dashboard"); 
} 

我遇到了相同的錯誤,並且稍微挖了一點Ember源代碼。在我的情況下,這個錯誤是由ControllerMixin拋出,因爲get(this, 'target')nullthis line。測試模塊可能不知道什麼target應該在這樣的控制器單元測試中沒有進一步的上下文,因此您可能需要手動設置它或繞過它。

0

由於您對轉換本身並不感興趣,因此您可以將transitionToRoute方法存放在控制器上。

JS:

test('Name', function() { 
    var controller = this.subject(); 
    controller.transitionToRoute = Ember.K; 
    ... 
} 

咖啡:

test "it exists", -> 
    controller = @subject() 
    controller.transitionToRoute = Ember.K 
    ok controller 
0

不知道爲什麼,當你在單元測試中執行它transitionToRoute方法是不確定的 - 它可能涉及到的事實,執行上下文不同。

對此的一個可能的解決方法是如果您將transitionToRoute調用移動到路由而不是它在控制器中。這樣你的控制器就會把動作發送到它的路由,並且你只會在路由中保持路由。

圍繞哪個更好的實踐有一個大討論 - 從控制器路由或不是,但這是另一回事。

相關問題