单元测试 – Ember CLI控制器测试:未捕获的TypeError:无法读取null的属性’transitionToRoute’

我有一个控制器,我正在使用Ember CLI进行测试,但控制器的承诺无法解决,因为控制器的transitionToRoute方法返回null:

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: "user@pass.com",
        password: "pass"
    }
    controller = @subject()
    Ember.run(->
        controller.setProperties({
            username: "user@pass.com",
            password: "pass"
        })
        controller.login().then(->
            token = controller.get("token")
            ok(controller.get("token") isnt null)
            equal(controller.get("token").length, 64)
        )
    )

当删除@transitionToRoute(“dashboard”)行时,测试通过;否则,测试失败.

如何在保持控制器逻辑的同时修复此错误?

最佳答案 解决方法:如果target为null,则绕过transitionToRoute.就像是:

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

我遇到了同样的错误并且稍微挖了一下Ember源代码.在我的情况下,这个错误是由ControllerMixin引发的,因为get(this,’target’)在this line为空.测试模块可能不知道在没有进一步的上下文的情况下这样的控制器单元测试应该是什么目标,所以你可能需要手动设置它或绕过它.

点赞