我如何在茉莉花中测试回调

时间:2015-06-25 08:59:27

标签: javascript unit-testing jasmine

我使用方法SomeClass.fetch()

的类SomeClass
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带参数?

1 个答案:

答案 0 :(得分:1)

你必须使用spyes:

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