Search code examples
unit-testingember.jscoffeescriptqunitember-cli

Ember CLI Controller Test: Uncaught TypeError: Cannot read property 'transitionToRoute' of null


I have a controller I'm testing with Ember CLI, but the controller's promise will not resolve, as the controller's transitionToRoute method is returning 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)
        )
    )

When the line @transitionToRoute("dashboard") is removed, the test passes; otherwise, the test fails.

How can I fix this error, while still maintaining my controller logic?


Solution

  • Work around: bypass transitionToRoute if target is null. Something like:

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

    I ran into the same error and dug into Ember source code a little bit. In my case this error is thrown by ControllerMixin because get(this, 'target') is null at this line. The test module probably has no idea what target should be in a controller unit test like this without further context, so you may need to manually set it or just bypass it.