Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$rootScope is undefined when testing with Karma

I am trying to write some unit tests for an angular project. I've followed some examples about testing a controller but I always end up with the same problem: $rootScope seems to be undefined.

My test.js:

describe("Unit: BodyCtrl", function() {

    var scope;

    beforeEach(function($rootScope, $controller) {
        scope = $rootScope.$new();
    });

    it('foo should be foo', function() {
        expect("foo").toBe("foo");
    });
})

and the error:

TypeError: Cannot read property '$new' of undefined'

I have included all the angular files in karma.conf.js. Could it cause problems that I have mounted the main application through sshfs from a server to my local Ubuntu 14.04 and Karma is installed on the said local machine?

like image 376
jjoonia Avatar asked Sep 13 '26 23:09

jjoonia


1 Answers

You need to inject it. Use inject in beforeEach, otherwise it is a mere variable defined in your function scope which is not defined with any value.

Example:-

beforeEach(inject(function($rootScope, $controller) {
    scope = $rootScope.$new();
    ctrl = $controller('yourcontroller', {
        $scope: $rootScope.$new()
    });
}));
like image 185
PSL Avatar answered Sep 16 '26 08:09

PSL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!