使用Jasmine与裸函数和RequireJS的成语

时间:2015-08-17 16:24:28

标签: javascript function testing mocking jasmine

使用Jasmine和RequireJS时,我可以采用什么方法来模拟裸函数?

据我所知,我不能方便地使用spyOn,因为这需要函数是一个方法的对象。虽然我可以获取此对象(RequireJS context.defined对象),但在bareFunctionfoo.js的分配已经在测试运行时发生,在测试时间(IIUC)不可能改变该功能。

裸function.js

define(function() {
  return function bareFunction() {
    return 'a';
  };
});

foo.js

define(function(require){
  var bareFunction = require('bare-function');

  return {
    doSomething: function() {
      var v = bareFunction();
      return v.toUpperCase();
    }
  };
}

FOO单元-test.js

define(function(require) {
  var bareFunction = require('bare-function');
  var target = require('foo');

  describe('foo', function(){

    describe('doSomething', function(){

      it('should uppercase the result of the bare-function', function() {
        //arrange
        var bareFunctionResult = 'test value';
        bareFunction.mockWith(function() { return bareFunctionResult; }); // Pseudocode.

        //act
        var result = target.doSomething();

        //assert
        expect(result).toBe(bareFunctionResult.toUpperCase());  
      });

    });

  });

});

我能想到的最好的方法是将一个__stub方法附加到裸功能上,如果设置了这个功能,则会使功能短路。 e.g。

裸function.js

define(function() {

  var stub;

  function bareFunction() {
    if(stub) {
      return stub();
    }

    return 'a';
  };

  bareFunction.__stub = function(v) {
    stub = v;
  };

  bareFunction.__unstub = function() {
    stub = null;
  };

  return bareFunction;
});

1 个答案:

答案 0 :(得分:0)

最后,我修改了foo.js,以便doSomething接受bareFunction的可选阴影函数,从而实现琐碎的存根/模拟。

<强> foo.js

define(function(require){
  var bareFunction = require('bare-function');

  return {
    doSomething: function(bareFunctionShadow) {
      var fn, v;
      fn = bareFunctionShadow || bareFunction;
      v = fn();
      return v.toUpperCase();
    }
  };
}

<强> FOO单元-test.js

define(function(require) {
  var bareFunction = require('bare-function');
  var target = require('foo');

  describe('foo', function(){

    describe('doSomething', function(){

      it('should uppercase the result of the bare-function', function() {
        //arrange
        var bareFunctionResult = 'test value';
        var bareFunctionMock = function() { return bareFunctionResult; };

        //act
        var result = target.doSomething(bareFunctionMock);

        //assert
        expect(result).toBe(bareFunctionResult.toUpperCase());  
      });

    });

  });

});