超时后的Chai断言

时间:2016-07-15 12:15:48

标签: javascript node.js unit-testing mocha chai

我有一些处理传出和传入数据的代码。当我发送请求时,我希望从外部来源获得某种答案。如果在超时1500ms后没有回答,我会返回错误回调并结束请求。这一切看起来像这样:

this.sendRequest = function(sendRequestDevice, sendRequestFID, sendRequestParam, sendRequestAction, sendRequestData,
                                sendRequestReturnCB, sendRequestErrorCB) {
        if (!this.isConnected) {
            if (sendRequestErrorCB !== undefined) {
                sendRequestErrorCB(VacuumSystem.ERROR_NOT_CONNECTED);
            }
            return;
        }
        // Packet creation
        var sendRequestAddress = this.getDeviceAddress(sendRequestDevice);
        var sendRequestPacket = pack(sendRequestAddress, sendRequestAction, sendRequestParam, sendRequestData);
       // var sendRequestSEQ = this.getSequenceNumberFromPacket(sendRequestHeader);
        // Sending the created packet
        if (sendRequestDevice.expectedResponse.length === 0) {
                // Setting the requesting current device's current request
            sendRequestDevice.expectedResponse.push({
                FID: sendRequestFID,
                timeout: setTimeout(this.sendRequestTimeout.bind
                (this, sendRequestDevice, sendRequestErrorCB), this.timeout),
                returnCB: sendRequestReturnCB,
                errorCB: sendRequestErrorCB
            });
            this.serialport.write(sendRequestPacket);
        } else {
            setTimeout(this.sendRequest.bind(this, sendRequestDevice, sendRequestFID, sendRequestParam,
                sendRequestAction, sendRequestData, sendRequestReturnCB, sendRequestErrorCB ), 1000)
        }
    };
    this.sendRequestTimeout = function (timeoutDevice, timeoutErrorCB) {
        // if the response is not received in 'this.timeout' ms, throw an error

        clearTimeout(timeoutDevice.expectedResponse[0].timeout);
        timeoutDevice.expectedResponse.splice(0, 1);
        if (timeoutErrorCB !== undefined){
            timeoutErrorCB(VacuumSystem.ERROR_TIMEOUT);
            console.log('Error Timeout');
        }
        return;
    };

我想使用mocha和chai进行单元测试来测试这种行为。基本上我只想声明错误回调是在1.5s之后使用参数 VacuumSystem.ERROR_TIMEOUT 调用的。我试过的是:

describe('behavior', function() {
    beforeEach(function () {
        returnCallback = sinon.spy();
        errorCallback = sinon.spy();
        // this function calls the sendRequest function with the needed parameters
        PPT100.getPressure(returnCallback, errorCallback);
    });
    it('should return a Timeout Error when no response is received', function (done) {
        setTimeout(function () {
           expect(errorCallback.callCount).to.equal(1);
           sinon.assert.calledWith(errorCallback, VacuumSystem.ERROR_TIMEOUT)
           done();
        }, PPT100.ipcon.timeout);
    });
});

我知道错误已经返回,因为我可以看到日志消息' Error Timeout'但是期望sinon间谍失败。我在这里做错了什么?

0 个答案:

没有答案
相关问题