1

I have a controller that sets a variable as follows:

terminalController.controller('GeneralSettingsController', [ '$rootScope', '$scope', 'GeneralSettingsService', 'getGeneralSettings', 
                   function($rootScope, $scope, GeneralSettingsService, getGeneralSettings) {

    getGeneralSettings.get().$promise.then(function (response) {
        $scope.connectionsettings = response;

        if(response.screenSaverOn == 'true') {
            $scope.screenSaver = 'On';
        } else {
            $scope.screenSaver = 'Off';
        }
     });
}
]);

Now I want to test that if the response has a screenSaverOn == 'true', that the $scope.screenSaver would be 'On'

This is my tests snippet:

    describe('GeneralSettingsController', function() {

        var rootScope, getConnectionSettings, resp;


        beforeEach(inject(function($controller,
                $rootScope, _$httpBackend_) {       

            rootScope = $rootScope.$new();
            $httpBackend = _$httpBackend_;
            $controller('GeneralSettingsController', {
                $rootScope : rootScope
            });

            $httpBackend.when('GET', 'ws/Admin/terminal/settings').respond(
                     { response : {
                        "screenSaverOn" : true
                     }
                    });
    }));
it('should call get connection settings when page is loaded', function() {
        $httpBackend.flush();

    assert.equal(rootScope.connectionsettings.response.screenSaverOn, true);
assert.equal(rootScope.screenSaver, 'On');


});

The first assert succeeds and the second fails, what am I doing wrong?

1 Answers1

0

The problem is that you are not injecting the required service into the controller. It is calling getGeneralSettings.get() but getGeneralSettings is never injected, so this should lead into an error. You only provided $rootScope. $scope, GeneralSettingsService, getGeneralSettings are missing.

You must provide your own mock object that simply responds with the response you want directly. And remove the HTTP back end mocking, as you are not using $http.

juunas
  • 54,244
  • 13
  • 113
  • 149
  • Hello Junnas, thanks for your answer... But if I remove the http, it fails saying: GeneralSettingsController... FAILED Unexpected request: GET ws/Admin/terminal/settings – Marianne Abdelmalek Jan 26 '15 at 12:47
  • I assume you are writing a unit test here. That means you have to replace all dependencies with mocks or stubs. This includes your service which is making a call with $http. Now it is injecting the real service, which is not how it should work in a unit test. – juunas Jan 26 '15 at 13:31
  • You have to make separate tests which test the service, in these tests the real service should not be injected. – juunas Jan 26 '15 at 13:32