我有一个返回 Promise 的 Node.js 函数。我正在使用Sinon.JS stubs来解决 promise 。代码中的 console.log 语句显示 stub 正在工作。但是,返回的是 {}
,而不是 Promise 解析的结果。
我查看了其他这些帖子,但都不是我遇到的问题:
这是函数:
function publishMessage(pubsub, topicName, data) {
const topic = pubsub.topic(topicName);
const publisher = topic.publisher();
return publisher.publish(data)
.then((results) => {
const messageId = results[0];
return messageId;
})
.catch((error) => {
console.log('Error ', error);
return error;
}); };
这是测试:
describe('publishMessage', function() {
describe('Success', function() {
it('should return the messageId', function(done) {
var publishMessage = index.__get__('publishMessage');
var promise = sinon.stub().resolves(['1111']);
var publisher = {
publish: promise
};
var topic = {
publisher: sinon.stub().returns(publisher)
};
var pubsub = {
topic: sinon.stub().returns(topic)
};
assert.equal('1111', publishMessage(pubsub, 'st', 'ds'));
assert.isTrue(topic.publisher.calledWith());
done();
});
});
});
当我执行测试时,console.log
的输出显示已打印解析值:
publishMessage
Success
1) should return the messageId
1111
0 passing (256ms)
1 failing
1) publishMessage
Success
should return the messageId:
AssertionError: expected '1111' to equal {}
at Context.<anonymous> (test/index.spec.js:63:14)
最佳答案
我注意到一些潜在的问题领域。
首先,我没有看到 index
的定义位置,因此我无法确认您期望的函数是否是从 index.__get__('publishMessage');
返回的。您可以通过目视检查结果来确认返回了正确的函数
publishMessage.toString();
我看到的另一个问题(更有可能是问题的原因)是,您从 publishMessage()
返回一个 Promise,但将对该函数的调用结果与 Promise 最终解析的值进行比较。换句话说,您将 Promise 与 String 进行比较。除非你的断言库在检查结果之前等待 Promise 解析(类似于 Jasmine),否则你将字符串与 Promise 进行比较。要解决这个问题,只需等待 Promise 解决即可:
it('should return the messageId', function(done) {
// Set up the test case by defining publishMessage, etc.
publishMessage(pubsub, 'st', 'ds').then((result) => {
assert.equal(result, '1111');
assert.isTrue(topic.publisher.calledWith());
done();
}).catch(done);
}
注意,我在 Promise 上添加了 .catch()
。这可以确保 Promise 中抛出的任何错误都会显示适当的错误,而不仅仅是超时错误。
如果您使用的是 Mocha 或 Karma/Jasmine 等测试框架,您可以通过直接返回 Promise 而不是使用 done()
来进一步改进这一点。根据我的经验,在尝试调试使用 Promise 的测试用例时,返回 Promise 会带来更好的堆栈跟踪和更有用、更准确的错误消息。举个例子:
it('should return the messageId', function() {
// Set up the test case by defining publishMessage, etc.
return publishMessage(pubsub, 'st', 'ds').then((result) => {
assert.equal(result, '1111');
assert.isTrue(topic.publisher.calledWith());
});
}
请注意,我不再接受测试用例中的参数。在 Mocha 和 Karma 中,框架就是这样决定如何处理测试用例的。
关于node.js - 解决promise的Sinon.JS stub 返回 "{}",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48033830/