Javascript 超时后重新启动
我有一些处理传出和传入数据的代码。当我发送请求时,我希望从外部来源得到某种答复。如果在1500毫秒的超时后没有收到任何答复,我将返回一些内容到错误回调并结束请求。这一切看起来都是这样的:Javascript 超时后重新启动,javascript,node.js,unit-testing,mocha.js,chai,Javascript,Node.js,Unit Testing,Mocha.js,Chai,我有一些处理传出和传入数据的代码。当我发送请求时,我希望从外部来源得到某种答复。如果在1500毫秒的超时后没有收到任何答复,我将返回一些内容到错误回调并结束请求。这一切看起来都是这样的: this.sendRequest = function(sendRequestDevice, sendRequestFID, sendRequestParam, sendRequestAction, sendRequestData, sendReq
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\u 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 spy,expect失败。我做错了什么