0

Can’t figure out how to make controller tests working. I am playing with ngStart seed project. So I forked the repository (https://github.com/Havrl/ngStart ) and want to create a very basic unit test.

My controller test file:

define(function() {
"use strict";
describe("the contactcontroller", function () {
    var contactController, scope;

    beforeEach(function () {
        module("contact");

        inject(["ContactController", function (_contactController) {
            contactController = _contactController;
        }]);
    });


    it("should give me true", function () {
        expect(true).toBe(true);
    });
});

});

But that is not working.

What am I missing?

1 Answer 1

3

as answered in the following question the controller needs to be manually instantiated with a new scope:

how to test controllers created with angular.module().controller() in Angular.js using Mocha

Additionally the project you are using (its mine :-) ) is defining the controllers inside route definitions and not with a call to angular.controller(...).

The downside is that the controllers are not known by name to angularJS (afaik), so the code from the answer above would not work:

ctrl = $controller("ContactController", {$scope: scope });

Instead you have to load the controller explicitely with requireJS inside your test file and give the function to the $controller(..) call, like this:

define(["ContactController"], function(ContactController) {
"use strict";
describe("the contactcontroller", function () {
    var contactController, scope;

    beforeEach(function () {
        module("contact");

        inject(["$rootScope", "$controller", function ($rootScope, $controller) {
            scope = $rootScope.$new();
            contactController = $controller(ContactController, {$scope: scope});
        }]);
    });

    ....
});
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.