power_pugg
power_pugg

Reputation: 11

Jasmine new function in function error

This is angular javascript source

var app = angular.module("myApp", []);

app.factory('AAA', function(){
    return function(){
        return {
            say:function(){
            console.log('I am A');
            }
        };
    };
});

app.factory('helpMe', function(AAA){
    return function(){

        var type = new AAA();

        var play = function(){
            type.say();  
        };

        return {
            play:play
        }

    };
});

This is Jasmine Source

    it('helMe Test',function(){
        var helpMe = new helpMe();
        var AAA = new AAA();

        spyOn(AAA,'say');
        helpMe.play();
        expect(AAA.say).toHaveBeenCalled();

    });

Jasmine souce is not working because new AAA() in helpMe factory, and new AAA in it(){} is different.

Upvotes: 0

Views: 24

Answers (1)

JB Nizet
JB Nizet

Reputation: 691685

You're missing the whole point of dependency injection, which is precisely to avoid creating instances of collaborators, and let the framework inject them instead, to make the code testable.

Here's a rewritten version of your code:

var app = angular.module("myApp", []);

app.factory('AAA', function() {
    return {
       say: function() {
           console.log('I am A');
       }
    };
});

app.factory('helpMe', function(AAA) {
    var play = function() {
        AAA.say();  
    };

    return {
        play: play
    };
});

And the test:

it('helMe Test', inject(function(AAA, helpMe) {
    spyOn(AAA, 'say');
    helpMe.play();
    expect(AAA.say).toHaveBeenCalled();
}));

Upvotes: 2

Related Questions