Ashwini
Ashwini

Reputation: 391

How to unit test the following function in jasmine?

I have a following code:

    angular
        .module('testApp')
        .factory('testDataService', function ($http) {
            function testDataService(){
                var self = this;
                self.test = function(){
                    //do something
                }

                self.test1 = function(){
                    // do something                
}
            }

            return new testDataService();

When I try to write a test case like 

    beforeEach(function(){
        new testDataService();
    });

It gives some error like:

> TypeError: '[object Object]' is not a constructor (evaluating 'new testDataService()')

There are numerous functions such as "test", "test1", etc.. inside testDataService. I am not able to test the remaining functions because the scope of the outer function is unreachable. I am not able to get the instance because of "var self=this" Please help.

Upvotes: 0

Views: 605

Answers (2)

RIYAJ KHAN
RIYAJ KHAN

Reputation: 15292

There is no need of new operator to create Object.

Please check this one

describe("\n\Testing factory", function () {
        var factTestDataService;

        beforeEach(inject(function (testDataService) {
           factTestDataService= testDataService;
        }))


        it("factTestDataService test to defined",function(){

            expect(factTestDataService.test()).toBeDefined()
        })
        it("factTestDataService test1 to defined",function(){

            expect(factTestDataService.test1()).toBeDefined()
        })

         it("factTestDataService to defined",function(){

            expect(factTestDataService).toBeDefined()
        })          
    });

You need to inject testDataService factory and store it in local var.

Then you can use this one to access the method defined in that factory as you do in angular and can check with different Jasmine test method.

Upvotes: 1

gfpacheco
gfpacheco

Reputation: 3215

Your factory already returns a new instance of testDataService. There's no need for calling new. When you try to call new on an instance it throws the error you see.

Upvotes: 0

Related Questions