簡體   English   中英

我如何在茉莉花中測試回調

[英]How i can test callback in jasmine

我有類SomeClass與方法SomeClass.fetch()

var repository = {
    get: function(obj) {
        //...
    }
};

var cache = false;

var SomeClass = {

    init: function() {
        //...
    },

    fetch: function () {
        var _this = this;

        repository.get({
            method: 'getRecentDialogsList',
            success: function (result) {
                if (!cache) {
                    _this.set(result);
                    _this.sort();
                    _this.trigger('fetch:success', _this);
                }

                _this.trigger('fetch:ajaxSuccess', _this);
            }
        });
    }
}

我如何才能測試SomeClass.fetch()並檢查是否已使用參數調用this.set()this.sortthis.trigger

您必須使用間諜:

describe("SomeClass Test", function() {
    it("calls the set() method when fetch is called", function() {
        spyOn(SomeClass, "set");
        SomeClass.fetch();
        expect(SomeClass.set).toHaveBeenCalled();
    });
});

您甚至可以用以下內容完全替換被調用的方法(例如,如果需要很長時間才能完成):

spyOn(SomeClass, "set").and.callFake(function myFakeSet() {
  console.log("I've been called");
});

暫無
暫無

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

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