【问题标题】:How to mock inline requirejs dependencies with squire for unit testing?如何使用 squire 模拟内联 requirejs 依赖项以进行单元测试?
【发布时间】:2014-10-09 01:51:25
【问题描述】:

我正在使用带有内联要求的 requirejs,例如:

define(['someDep'], function(someDep) {
  return {
    someFn: function() {
      require(['anotherDep'], function(anotherDep) {
        anotherDep.anotherFn();
      });
    }
  } 
});

在我的特殊情况下,我不能在定义中包含 anotherDep

在使用 mocha 进行测试时,我有一个这样的测试用例:

define(['squire'], function(Squire) {
  var squire = new Squire();
  describe('testcase', function() {
    it('should mock anotherDep', function(done) {
      var spy = sinon.spy();
      squire.mock('anotherDep', {
        anotherFn: spy
      });
      squire.require(['someDep'], function(someDep) {
        someDep.someFn();
        expect(spy).to.have.been.calledOnce;
        done();
      });
    });
  });
});

失败是因为anotherDep 直接调用require 而不是squire.require。解决方法是在全局范围内替换require

var originalRequire;

before(function() {
  originalRequire = require;
  require = _.bind(squire.require, squire);
});

after(function() {
  require = originalRequire;
});

这行得通(注意squire.require 必须以某种方式绑定到squire 对象,我使用下划线来执行此操作)但由于时间原因仍不会调用间谍。测试也必须更改为

it('should mock anotherDep', function(done) {
  squire.mock('anotherDep', {
    anotherFn: function() {
      done();
    }
  });
  squire.require(['someDep'], function(someDep) {
    someDep.someFn();
  });
});

有没有更好的方法?如果没有,希望这能为遇到同样问题的其他人提供解决方案。

【问题讨论】:

    标签: javascript unit-testing requirejs mocha.js squirejs


    【解决方案1】:

    我没有尝试专门做你想做的事情,但在我看来,如果 squire 做得很彻底,那么需要 require 模块应该会给你想要的东西,而不必弄乱全球requirerequire 模块是一个特殊的(和保留的)模块,它使本地require 函数可用。例如,当您使用 Common JS 语法糖时,这是必需的。但是,只要您想获得本地 require,就可以使用它。同样,如果 squire 做得很彻底,那么它给你的 require 应该是一个 squire 控件,而不是某种原始的 require

    所以:

    define(['require', 'someDep'], function (require, someDep) {
      return {
        someFn: function() {
          require(['anotherDep'], function(anotherDep) {
            anotherDep.anotherFn();
          });
        }
      } 
    });
    

    【讨论】:

    • 这非常有效。起初我犹豫是否要修改我的模块以包含依赖于“require”作为一个模块,因为它看起来有点笨拙和不必要,但经过一番思考,我意识到这真的是关于编写可测试的代码,如果这样做可以让代码成为单元-testable 那么这是一个值得实施的模式。
    • 很高兴为您提供帮助!请注意,这里没有黑客攻击。将 require 放在依赖项中是 RequireJS 的公共 API 的一部分,实际上对于某些用例是必要的(除了我在回答中提到的那个)。
    猜你喜欢
    • 2012-07-11
    • 2015-08-25
    • 2017-03-22
    • 2013-08-20
    • 2023-03-13
    • 2014-05-29
    • 1970-01-01
    • 1970-01-01
    • 2016-02-19
    相关资源
    最近更新 更多