Correct way to mock an AngularJS Service in a unit test?

Sam

I have the following controller and service that I am trying to write tests around in Jasmine. I am fairly new to this, and just wanted to see if I am taking the correct approach in testing and mocking my services.

Controller

(function () {
    'use strict';

    var app = angular.module('cs');

    app.controller('PlateCheckCtrl', ['$scope', 'PlateCheckService', function ($scope, PlateCheckService) {
        var plateCheck = {
            plateNumber: '',
            message: '',
            alertClass: '',
            checkPlate: function (plateNumber) {
                var _this = this;

                PlateCheckService.checkPlate(plateNumber).then(function (response) {
                    _this.message = response.message;
                    _this.alertClass = response.alertClass;
                });
            }
        };

        $scope.plateCheck = plateCheck;
    }]);

}());

Service

(function () {
    'use strict';

    var app = angular.module('cs');

    app.service('PlateCheckService', ['$http', function ($http) {
        return {
            checkPlate: function (plateNumber) {
                return $http.post('PlateCheck/Index', {
                    plateNumber: plateNumber
                }).then(function (response) {
                    return {
                        message: response.data.VehicleAtl === null ? 'Clean' : 'Hot',
                        alertClass: response.data.VehicleAtl === null ? 'alert-success' : 'alert-danger'
                    };
                });
            }
        };
    }]);

}());

Controller Test

describe('Spec Template', function () {
    var scope,
        controller;

    beforeEach(function () {
        module('cs');

        inject(function ($rootScope, $controller, $q) {
            scope = $rootScope.$new();

            controller = $controller('PlateCheckCtrl', {
                $scope: scope, PlateCheckService: {
                    checkPlate: function (plateNumber) {
                        var d = $q.defer();

                        if (plateNumber === '123') {
                            d.resolve({
                                message: 'Clean',
                                alertClass: 'alert-success'
                            })
                        } else {
                            d.resolve({
                                message: 'Hot',
                                alertClass: 'alert-danger'
                            })
                        }

                        return d.promise;
                    }
                }
            });
        });
    });

    it('Should return "Clean" result', function () {
        scope.plateCheck.checkPlate('123');
        scope.$apply();
        expect(scope.plateCheck.message).toBe('Clean');
        expect(scope.plateCheck.alertClass).toBe('alert-success');
    });

    it('Should return "Hot" result', function () {
        scope.plateCheck.checkPlate('123456');
        scope.$apply();
        expect(scope.plateCheck.message).toBe('Hot');
        expect(scope.plateCheck.alertClass).toBe('alert-danger');
    });

});

Service Tests

describe('Plate Check Service', function () {
    var httpBackend,
        service;

    beforeEach(function () {
        module('cs');

        inject(function ($httpBackend, PlateCheckService) {
            httpBackend = $httpBackend;
            httpBackend.whenPOST('PlateCheck/Index', { plateNumber: '123' }).respond({ VehicleAtl: null });
            httpBackend.whenPOST('PlateCheck/Index', { plateNumber: '123456' }).respond({ VehicleAtl: {} });
            service = PlateCheckService;
        });
    });

    afterEach(function () {
        httpBackend.verifyNoOutstandingExpectation();
        httpBackend.verifyNoOutstandingRequest();
    });

    it('Should send the request to the server', function () {
        httpBackend.expectPOST('PlateCheck/Index', { plateNumber: '123' });
        service.checkPlate('123');
        httpBackend.flush();
    });

    it('Should return a "Clean" result', function () {
        var result;

        service.checkPlate('123').then(function (response) {
            result = response;
        });

        httpBackend.flush();

        expect(result.message).toBe('Clean');
        expect(result.alertClass).toBe('alert-success');
    });

    it('Should return a "Hot" result', function () {
        var result;

        service.checkPlate('123456').then(function (response) {
            result = response;
        });

        httpBackend.flush();

        expect(result.message).toBe('Hot');
        expect(result.alertClass).toBe('alert-danger');
    });
});
Sten Muchow

Your controller doesnt actually have any functionality only the service does. So you shouldnt be testing the service functionality in the controller.

describe('Spec Template', function () {
var scope,
    controller,
    PlateCheckServiceMock = {
         checkPlate: function () {}
    };  


beforeEach(function () {
    module('cs');

    inject(function ($rootScope, $controller, $q) {
        scope = $rootScope.$new();
        spyOn(PlateCheckService, 'checkPlate').andCallThrough();
        controller = $controller('PlateCheckCtrl', {
            $scope: scope, 
            PlateCheckService: PlateCheckServiceMock
          }
        });
    });
});

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

how to mock $window to unit test AngularJS service?

From Dev

Angularjs Unit Test for Service

From Dev

Correct way to make a mock test

From Dev

How to mock AngularFire 2 service in unit test?

From Dev

Grails Spock Mock Injected Service in Unit Test

From Dev

How to mock AngularFire 2 service in unit test?

From Dev

mock angularjs service for unit testing using jasmine

From Java

How do I mock a service that returns promise in AngularJS Jasmine unit test?

From Dev

AngularJS override (mock) services for unit test

From Dev

angularjs unit test karma with jasmine mock dilemma

From Dev

AngularJS override (mock) services for unit test

From Dev

Correct way to unit test the type of an object

From Dev

AngularJS Controller As Jasmine test with mock service with promise

From Dev

How to test function in AngularJS service with mock data

From Dev

AngularJS - unit tests - using original service from mock of same service?

From Dev

Unit test service that returns promise Angularjs Jasmine

From Dev

Unit test service that returns promise Angularjs Jasmine

From Dev

How to unit test an AngularJS service / factory

From Dev

Is this the correct way to mock HttpContextBase, HttpRequestBase and HttpResponseBase for Unit Testing Cookies?

From Dev

Is this the correct way to mock HttpContextBase, HttpRequestBase and HttpResponseBase for Unit Testing Cookies?

From Dev

Mock a controller for unit test without any service reference C#

From Dev

Angularjs: mock location.path() with spyOn for a unit test

From Dev

How do I mock the result of a promise in an AngularJS unit test?

From Dev

How to mock $window.location.replace in AngularJS unit test?

From Dev

How do I mock the result of a promise in an AngularJS unit test?

From Dev

How to mock an event like 'keypress' or 'keydown' in an AngularJS unit test?

From Dev

Angularjs: mock location.path() with spyOn for a unit test

From Dev

AngularJS + Jasmine mock unit test $http factory of POST method

From Dev

Better way to mock class attribute in python unit test

Related Related

  1. 1

    how to mock $window to unit test AngularJS service?

  2. 2

    Angularjs Unit Test for Service

  3. 3

    Correct way to make a mock test

  4. 4

    How to mock AngularFire 2 service in unit test?

  5. 5

    Grails Spock Mock Injected Service in Unit Test

  6. 6

    How to mock AngularFire 2 service in unit test?

  7. 7

    mock angularjs service for unit testing using jasmine

  8. 8

    How do I mock a service that returns promise in AngularJS Jasmine unit test?

  9. 9

    AngularJS override (mock) services for unit test

  10. 10

    angularjs unit test karma with jasmine mock dilemma

  11. 11

    AngularJS override (mock) services for unit test

  12. 12

    Correct way to unit test the type of an object

  13. 13

    AngularJS Controller As Jasmine test with mock service with promise

  14. 14

    How to test function in AngularJS service with mock data

  15. 15

    AngularJS - unit tests - using original service from mock of same service?

  16. 16

    Unit test service that returns promise Angularjs Jasmine

  17. 17

    Unit test service that returns promise Angularjs Jasmine

  18. 18

    How to unit test an AngularJS service / factory

  19. 19

    Is this the correct way to mock HttpContextBase, HttpRequestBase and HttpResponseBase for Unit Testing Cookies?

  20. 20

    Is this the correct way to mock HttpContextBase, HttpRequestBase and HttpResponseBase for Unit Testing Cookies?

  21. 21

    Mock a controller for unit test without any service reference C#

  22. 22

    Angularjs: mock location.path() with spyOn for a unit test

  23. 23

    How do I mock the result of a promise in an AngularJS unit test?

  24. 24

    How to mock $window.location.replace in AngularJS unit test?

  25. 25

    How do I mock the result of a promise in an AngularJS unit test?

  26. 26

    How to mock an event like 'keypress' or 'keydown' in an AngularJS unit test?

  27. 27

    Angularjs: mock location.path() with spyOn for a unit test

  28. 28

    AngularJS + Jasmine mock unit test $http factory of POST method

  29. 29

    Better way to mock class attribute in python unit test

HotTag

Archive