0

I'm running into a problem while trying to test my controller.

I'll just throw the code out here and after that explain what the problem is.

Controller

// Controller name is handy for logging
var controllerId = 'splash';

// Define the controller on the module.
// Inject the dependencies. 
// Point to the controller definition function.
angular.module('app').controller(controllerId,
    ['$scope', 'datacontext', splash]);

function splash($scope, datacontext) {
    // Using 'Controller As' syntax, so we assign this to the vm variable (for viewmodel).
    var vm = this;

    // Bindable properties and functions are placed on vm.
    vm.activate = activate;
    vm.title = 'Splash';
    vm.getRooms = function () {
        return vm.rooms;
    }
    activate();
    return vm;
    function activate() {
        datacontext.getRooms().then(function (data) {
            vm.rooms = data;
        });

    }
}

Datacontext method

function getRooms() {
        var deferred = Q.defer();
        deferred.resolve([{ id: 1, Name: "A02" }, { id: 2, Name: "A03" }]);
        return deferred.promise;
    }

Test

it('should have a splash title', inject(function($q, datacontextMock) {
    var vm = testContext.$controller('splash', { $scope: scope, datacontext: datacontextMock });

    expect(vm.title).toEqual('Splash');
    expect(vm.rooms).not.toBeNull();

    console.log(vm);
    expect(vm.rooms).toEqual(testContext.rooms);
}));

The problem is, the test fails. It will tell me that vm.rooms is undefined...but it isn't. When logging the vm with console.log, i can actually just click through the vm object and see a rooms array there, which is the array returned by the datacontext.

Why is this telling me vm.rooms is undefined?

1 Answer 1

1

Solved it. Ended up using $q instead of Q (which is advised anyway, but didn't seem to work before).

Also, in the test i now have a call to the activate method on the controller like this:

scope.$digest(vm.activate());

That solved it for me.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.