How to test internal functions, which are needed for internal purposes, using Jasmine

我的未来我决定 提交于 2019-12-11 03:17:42

问题


(function(window,document){

  var _trimString = function( string ){
     var trimString;
     trimString = string.replace(/^\s+|\s+$/g,'');
     return trimString
  };

  var displayCorrectText = function( incorrecttext ){
     correctText = "."+incorrecttext;
     document.write( correctText );
  }

  var Circular = function(){};

  Circular.prototype.init = function( string ){
     displayCorrectText( _trimString( string ) );
  };

  var circular = new Circular();
  window.circular = circular;
})(window,document);

circular.init('asd.asd');

I have this module declaration and i want to test _trimString function using Jasmine.

i wrote something like this code

describe("Form Creator private function ", function(){
it("_trimString should trim string", function(){
    var _trimString = function( string ){
        var trimString;
        trimString = string.replace(/^\s+|\s+$/g,'');

        return trimString
    };
 expect(_trimString('   test text  ') ).toBe('test text');
});

});

I'm doing it right, declaring the function itself in the test, or is there another way? if I did so function test, I think, wrong to copy the actual function in the source code. Maybe, someone could show me right case of using "private" function in module declaration


回答1:


I agree with Andy Waite: In general you should only test public interface methods.

However, if you think this private method really needs direct testing, this may be a symptom of a problem. It smells like this method is doing too much work (or at least something you consider significant work). If that's the case, consider extracting its logic into a service object and delegating to it. This way its easy to test the service object separately.

EDIT:

In code:

var Circular = function(){
  this.trimmer = new Trimmer();
};

Circular.prototype.init = function( string ){
  this.displayText = this.trimmer.trim( string );
};

var circular = new Circular();
circular.init("  test  ").displayText // should be trimmed

...

// test trimmer separately 
describe("Trimmer", function(){
   it("trims string", function(){ ... }); 
});



回答2:


In general you should only test the public interface methods.

Your initializer is calling _trimString so you can implicitly test it via that.

For example:

it("trims whitespace"), function(){
  var circular = Circular.new(' foo ')
  expect(circular.text).toBe('foo')
}

You may need to restructure some of your existing code to make this more testable. displayCorrectText currently has two distinct responsibilities - to manipulate some string and to print the result, which violates the Single Responsibility Principle.



来源:https://stackoverflow.com/questions/15248636/how-to-test-internal-functions-which-are-needed-for-internal-purposes-using-ja

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!