user3428816
user3428816

Reputation: 1301

How can I test one part of a js function using jasmine.js?

I have one of the backbones' view.js function as:

functionName : function(e){
     var a = $(e.currentTarget).val().replace(/\ /g, '+');

    // Remaining code (function behavior) here...

}

I need to check this var a = $(e.currentTarget).val().replace(/\ /g, '+'); line of code from jasmine framework for code coverage.

Please help me, How to test this line of code using jasmine.js (Version 1.3.1) framework?.

Upvotes: 0

Views: 99

Answers (1)

josephnvu
josephnvu

Reputation: 1242

You will need to splice your code in a way that it can be testable. Making code that is a testable, or actually writing tests in general is an skill in itself. In this situation you're gonna need to restructure your code a bit. Using what I see there, I would come up with this:

_padPlus: function( value ) {
    return value.replace(/\ /g, '+');
},

functionName: function(e) {
    var a = this._padPlus( $(e.currentTarget).val() );

    // Remaining code (function behavior) here...
}

From here, I would test _padPlus on it's own:

it('should replace spaces with plus signs', function(){
    // arrange
    var view = new View();
    var string = 'this is a sentence with spaces';

    // act
    var result = view._padPlus( string );

    // assert
    expect(result).toBe('this+is+a+sentence+with+spaces');
})

Upvotes: 1

Related Questions