如何使用Jasmine测试内部所需的内部函数

如何使用Jasmine测试内部所需的内部函数

本文介绍了如何使用Jasmine测试内部所需的内部函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(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');

我有这个模块声明,我想用Jasmine测试 _trimString 函数。

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

我写了类似这样的代码

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

推荐答案

我同意Andy Waite:一般情况你应该只测试公共接口方法。

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.

编辑:

在代码中:

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(){ ... });
});

这篇关于如何使用Jasmine测试内部所需的内部函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 08:00