Search code examples
angularjsjasmine

Angular / Jasmine fails to inject controller


I'm having trouble getting started using Jasmine and AngularJS. I've tried to create a minimal example, largely derived from the angular docs:

I have a module and a controller in testme.js:

(function(){
    "use strict";
    let cont = function($scope) {
        $scope.data = 99;
    };
    let app = angular.module('Test', []);
    app.controller('Cont', cont);
}());

I have a test TestSpec.js

"use strict";
console.log('launching test...');
describe('Test a test', function(){
    console.log('in describe...');
    
    beforeEach(angular.module('Test'));
    
    it('should create a number', inject(function($controller){
        let scope = {};

        console.log('in test...');
        let ctrl = $controller('Cont', {$scope:scope}); // fails here
        console.log('got controller...');
        expect(scope.data).toBe(99);
        console.log('test completed...');
    }));
});

And a SpecRunner.html

<!DOCTYPE html>
<html data-ng-app="Test">
    <head>
        <link rel="shortcut icon" type="image/png" href="jasmine/lib/jasmine-2.4.1/jasmine_favicon.png">
        <link rel="stylesheet" href="jasmine/lib/jasmine-2.4.1/jasmine.css">
        <script src="jasmine/lib/jasmine-2.4.1/jasmine.js"></script>
        <script src="jasmine/lib/jasmine-2.4.1/jasmine-html.js"></script>
        <script src="jasmine/lib/jasmine-2.4.1/boot.js"></script>

        <script src="scripts/angular.js"></script>
        <script src="scripts/angular-mocks.js"></script>

        <script src="scripts/testme.js"></script>    
        <script src="test/TestSpec.js"></script>
    </head>

    <body data-ng-controller="Cont">
        <h1>Value is {{data}}</h1>
    </body>
</html>

It seems like it starts up, and I get the messages

launching test... in describe... in test...

but it fails trying to execute the line I marked as // fails here, in TestSpec.js. This tells me that I'm not managing to retrieve the controller. Needless to say, I don't understand why (there are many questions on this topic, but they all seem not applicable here, as far as I can see).

Oh, and in case it's relevant, I'm using Angular 1.5:

Here's the screenshot of the various errors.


Solution

  • The error is here

    beforeEach(angular.module('Test'));
    

    It should be module.