摩卡测试模拟功能

巫师

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

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);
}

怎么做 ?

苏贝

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

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

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插件并将其简化为:

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

// Perform your test

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章