好吧,sandbox.stub(global, 'setTimeout', setImmediate); 似乎可以解决问题。谢谢@Esailija。
这是工作测试代码:
var chai = require('chai');
chai.use(require('sinon-chai'));
var expect = chai.expect;
var sinon = require('sinon');
var Promise = require('bluebird');
var TestService = {
waitForLongRunningTask: function (taskId) {
return TestService.checkTaskStatus(taskId)
.then(function (result) {
if (result.status == 'success') {
return Promise.resolve(result);
}
if (result.status == 'failure') {
return Promise.reject(result);
}
return Promise.delay(5000)
.then(function () {
return TestService.waitForLongRunningTask(taskId);
});
});
},
checkTaskStatus: function () {}
};
describe('waitForLongRunningTask', function () {
var promise, checkTaskStatus, taskId, sandbox, waitForLongRunningTask;
function setUp () {
taskId = 12345;
sandbox = sinon.sandbox.create();
waitForLongRunningTask = sandbox.spy(TestService, 'waitForLongRunningTask');
checkTaskStatus = sandbox.stub(TestService, 'checkTaskStatus');
sandbox.stub(global, 'setTimeout', setImmediate);
}
describe('when the task eventually succeeds', function () {
beforeEach(function () {
setUp();
checkTaskStatus.onCall(0).returns(Promise.resolve({
id: taskId,
status: 'in_progress'
}));
checkTaskStatus.onCall(1).returns(Promise.resolve({
id: taskId,
status: 'in_progress'
}));
checkTaskStatus.returns(Promise.resolve({
id: taskId,
status: 'success'
}));
});
afterEach(function () {
sandbox.restore();
});
it('should wait for the task to succeed and then resolve with the task results', function () {
return Promise.try(function () {
promise = TestService.waitForLongRunningTask(taskId);
return promise.finally(function () {
expect(promise.isFulfilled()).to.be.true;
expect(waitForLongRunningTask).to.have.been.calledThrice;
expect(checkTaskStatus).to.have.been.calledThrice;
expect(promise.value()).to.deep.equal({
id: taskId,
status: 'success'
});
});
});
});
});
describe('when the task eventually fails', function () {
beforeEach(function () {
setUp();
checkTaskStatus.onCall(0).returns(Promise.resolve({
id: taskId,
status: 'in_progress'
}));
checkTaskStatus.onCall(1).returns(Promise.resolve({
id: taskId,
status: 'in_progress'
}));
checkTaskStatus.returns(Promise.resolve({
id: taskId,
status: 'failure'
}));
});
afterEach(function () {
sandbox.restore();
});
it('should wait for the task to fail and then reject with the task results', function () {
return Promise.try(function () {
promise = TestService.waitForLongRunningTask(taskId);
return promise
.error(function () {})
.finally(function () {
expect(promise.isRejected()).to.be.true;
expect(waitForLongRunningTask).to.have.been.calledThrice;
expect(checkTaskStatus).to.have.been.calledThrice;
expect(promise.reason()).to.deep.equal({
id: taskId,
status: 'failure'
});
});
});
});
});
});
如果有人发现这种方法的任何问题,请告诉我!