user3045179
user3045179

Reputation: 331

$controller not getting instantiated in jasmine

This snippet of code is giving error when running my test case.

 beforeEach(module(function($scope) {

// do something interesting with the service
//console.log($controller);

}));

Error coming up in console.

debug.js:21 Uncaught Error: [$injector:modulerr] Failed to instantiate    
module function ($scope) due to:
Error: [$injector:unpr] Unknown provider: $scope

Could anyone please explain why it is not able to find $scope. It is also not working if I change it to $timeout or $controller.

Updated Code If I change the code to this

Then it works

module(function($controllerProvider) {
// we could also access the $controllerProvider.allowGlobals() function, 
// which allows us to register a controller on the window object.
$controllerProvider.register('ProductsController', function() {
    // logic of the controller...
});
});

Upvotes: 0

Views: 339

Answers (1)

just.another.programmer
just.another.programmer

Reputation: 8785

You're mixing up two different functions module and inject.

module configures the jasmine environment to use the angular module you specify. That's probably app. If you don't call this, the injector will not be able to find your services, controllers, directives, etc. In the module function, you can inject providers, not services, factories, etc. You use providers to configure how the services will behave later.

inject takes the function you supply and "injects" the services, constants, factories, etc by name before calling it. You use this to inejct the services etc themselves.

Here's a sample of how to split the calls in your code. I also changed the $scope to use $rootScope and create a scope.

 beforeEach(function() {
    module("app"); //or if your module is name something different, use that name instead

    inject(function($controller, $rootScope) {
        var $scope = $rootScope.$new();
        var myCtrl = $controller("myCtrl", { $scope: $scope });
    }));
});

Upvotes: 1

Related Questions