【问题标题】:Mocha tests mocking functionMocha 测试模拟功能
【发布时间】:2015-10-21 21:20:08
【问题描述】:

我正在测试具有功能的主干视图:

attachSelect: function(id, route) {
    console.log(id);
    console.log(route);

    this.$(id).select2({
        ajax: {
            url: route,
            dataType: 'json',
            results: function(data) {
                var results = _.map(data, function(item) {
                    return {
                        id: item.id,
                        text: item.title
                    };
                });

                return {
                    results: results
                };
            },
            cache: true
        }
    });
}

我需要重写(模拟)这个函数,看起来像:

attachSelect: function(id, route) {
    console.log(id);
    console.log(route);
}

如何做到这一点?

【问题讨论】:

  • 这取决于您的测试设置。您可以在创建后覆盖视图方法。喜欢this.someView.attachSelect = function (){};

标签: javascript backbone.js mocha.js sinon


【解决方案1】:

模拟函数的最简单方法是在运行时替换属性。

您可以提供自己的监控功能(通常称为间谍),尽管这不是最优雅的。看起来像:

var called = false;
var testee = new ViewUnderTest();
var originalAttach = testee.attachSelect; // cache a reference to the original
testee.attachSelect = function () {
  called = true;
  var args = [].concat(arguments); // get an array of arguments
  return originalAttach.apply(testee, args);
};

// Perform your test

expect(called).to.be.true;

如果您有像chai 这样的测试断言库,您可以使用spies plugin 并将其缩减为:

var testee = new ViewUnderTest();
var spy = chai.spy(testee.attachSelect);
testee.attachSelect = spy;

// Perform your test

expect(spy).to.have.been.called();

使用间谍库将提供一些有用的功能,例如监控调用次数及其参数以验证低级行为。如果您使用的是 Chai 或 Jasmine,我强烈建议您利用对间谍的相应支持。

【讨论】:

    猜你喜欢
    • 2018-11-06
    • 1970-01-01
    • 1970-01-01
    • 2017-03-27
    • 1970-01-01
    • 2021-10-13
    • 2016-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多