Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple unit test for Angular service

I have an Angular service that receives a number N (between 1-12) and returns the sum of integers up to 12 - N:

app.value('myNumberService', {
    calculateValue: function (n) {
        var empty = [];
        for(var i = 0; i < 12 - n; i++){
            empty.push(i);
        }
        return empty;
    }
});

I am trying to write a very basic unit test to check that the service is defined:

describe('app', function () {

    var app, service;

    beforeEach(function () {
        app = angular.mock.module('app')
    });

    beforeEach(inject(function($injector) {
        service = $injector.get('myNumberService');
    }));             

    describe('*Validating myNumberService service', function () {           
        describe("calculateValue", function(){
            it("should be defined.", function(){
                expect(service.calculateValue()).toBeDefined();
            });
        });
    });     
});

I receive this error:

PhantomJS 1.9.8 (Windows 7) app *Validating myNumberService service encountered a declaration exception FAILED
    TypeError: 'undefined' is not an object (evaluating 'service.calculateValue')

Any help appreciated.

like image 712
Oam Psy Avatar asked Sep 02 '26 02:09

Oam Psy


1 Answers

I'm not sure why your test is failing on first glance. However, it's got a lot of stuff that could be improved (and somewhere in the middle is probably the mistake). Here's how I'd write a unit test for that module:

describe('app', function () {

    var myNumberService;

    beforeEach(module(this.description));    // this.description === 'app'

    beforeEach(inject(function (_myNumberService_) {
        myNumberService = _myNumberService_;    // see documentation for `angular.mock.inject`
    }));

    describe('myNumberService', function () {

        it('calculates ...', function () {
            expect(myNumberService.calculateValue(...)).toBe(...);
        });
    });
});

As you can see, I don't actually test service's presence there. This is because if the service doesn't exist, tests requiring its injection will fail with a quite understandable error. Your unit tests should explicitly test just the functionality of your unit; basic integrity of your code will be tested implicitly. To give another example, you wouldn't test that calculateValue is a function. (The first test that tries to use it as a function will fail with "... is not a function" anyway, if it's not.)


Bonus hint: Sum of 1 + 2 + 3 + ... + n can be calculated simply as (n * (n + 1)) / 2.

like image 186
hon2a Avatar answered Sep 05 '26 10:09

hon2a