简体   繁体   中英

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM