簡體   English   中英

摩卡測試模擬功能

[英]Mocha tests mocking function

我正在測試具有功能的骨干視圖:

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,我強烈建議您充分利用對間諜的相應支持。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM