Backbone.js 昆特;西农。监视异步调用的函数

Backbone.js 昆特;西农。监视异步调用的函数,backbone.js,asynchronous,qunit,sinon,Backbone.js,Asynchronous,Qunit,Sinon,使用Sinon,我试图监视来自qunit测试中函数的异步函数调用: test("requestLiveCategoriesData should call parseCategoriesData", function(){ var spy = sinon.spy(this.liveCategoriesModel, 'parseCategoriesData'); this.liveCategoriesModel.requestLiveCategoriesData()

使用Sinon,我试图监视来自qunit测试中函数的异步函数调用:

test("requestLiveCategoriesData should call parseCategoriesData", function(){
        var spy = sinon.spy(this.liveCategoriesModel, 'parseCategoriesData');
        this.liveCategoriesModel.requestLiveCategoriesData();
        sinon.assert.calledOnce(spy);
    });
测试失败(
预期parseCategoriesData调用一次,但被调用0次
),即使parseCategoriesData确实被requestLiveCategoriesData调用-我知道这一点,因为当我在浏览器中运行测试时,
parseCategoriesData调用
被输出到控制台

这是我正在测试的代码(为了回答这个问题而简化):


我这样做是否正确?

您至少需要指示QUnit使用等待异步响应调用

现在,当您设置好该设置后,您需要确定何时可以调用
sinon.assert.calledOnce(spy)。看起来目前无法知道
LiveEventRequest
何时返回数据

如果您无法使用setTimeout修改当前代码,那么等待一点是您唯一的(坏)选项

如果您可以更改代码,您可能应该调查是否可以从
requestLiveCategoriesData
调用返回承诺。当数据到达时,让承诺解决问题。然后,您可以在执行Sinon检查之前等待该承诺,然后执行类似于QUnit异步文档中的done()调用

当我们这样做的时候:您可能应该使用sinon fakeserver或其他方式来模拟
LiveEventRequest
的结果

requestLiveCategoriesData: function () {
    console.log('getting live categories');
    try {
        console.log("--- RETRIEVING LIVE CATEGORIES EVENTS ---");

        liveCategoriesCall = new LiveEventRequest(eventObjRequest);
        liveCategoriesCall.on('reset', this.parseCategoriesData, this); //the spied on function is called from here
        liveCategoriesCall.fetch({ 
            success: function (collection, resp, options) { 
                console.log('Live Categories Events Request complete.');
            },
            error: function(collection, resp) {
                console.log("Error on Live Categories Events Request");
                if (_.has(resp, 'statusText') && resp.statusText === "timeout") {
                    /* Timeout error handling */
                    console.log("Live Categories Events Request Timeout");
                }
                Conf.generalNetworkError();
            },
            complete: function (resp, textStatus) {
                console.log("Live Categories Request teardown.");
                if (liveCategoriesCall) { liveCategoriesCall.off('reset', that.parseCategoriesData, that); }
            },
            cache:false,
            timeout: that.get('liveEventsTimeout')
        });

    } catch(err) {
        console.log("ERROR: PROCESSING LIVE CATEGORIES");
        console.log(err.message);
        console.log(err.stack);
        if (liveCategoriesCall) { liveCategoriesCall.off('reset', this.parseEventsData, this); }
        this.set({ 
            'lastRequest': (new Date()).getTime(),
            'liveCategories': []
        });
        this.trigger("errorAPI", err.message);
    }
},    


parseCategoriesData: function (liveCategoriesCall) {
    console.log('parseCategoriesData called');
},