【发布时间】:2021-07-26 07:49:32
【问题描述】:
使用 sinon,我试图窥探原型方法。它在在线howtos 等中看起来很简单。我尝试了很多网站和这样的帖子:Stubbing a class method with Sinon.js 或sinon - spy on toString method,但它对我不起作用。
先决条件
我正在使用 http.d.ts https://github.com/nodejs/node/blob/master/lib/_http_outgoing.js 通过 OutgoingMessage 对象从异步 API 调用写回数据:
class OutgoingMessage extends stream.Writable
OutgoingMessage中有一个原型方法end:
OutgoingMessage.prototype.end = function end(chunk, encoding, callback) {
我的 API 函数是这样调用的:
Get = async (req:IncomingMessage,res:OutgoingMessage):Promise<void> => {...
...
res.end(data)
...
}
我的测试
在我的测试中,我调用了Get 方法。我的IncomingMessage 决定了我期望在OutgoingMessage 中的内容。
it("should call end with the correct value", async function(){
...
let outgoingMessageSpy = sinon.spy(OutgoingMessage.prototype,"end");
let anOutgoingMessage = <OutgoingMessage>{};
...
expect(outgoingMessageSpy.calledOnce).to.be.true();
}
调试测试用例我看到end 是如何被调用的,但显然我没有以正确的方式设置我的间谍,因为我的期望失败了,calledOnce 是false。检查对象我发现calledCount 是0。
当我这样做时,我做的基本相同(在我看来)
const toStringSpy = sinon.spy(Number.prototype, "toString");
expect(toStringSpy.calledWith(2)).to.be.true;
这行得通。不过,我确实注意到,VS Code 以不同的方式突出显示关键字 prototype 为 Number.prototype 和 OutgoingMessage.prototype。这有关系吗?鼠标悬停时显示NumberConstructor.prototype,但只有OutgoingMessage.prototype..
问题
如何正确设置间谍来接听原型方法end的调用?
【问题讨论】:
标签: node.js mocking mocha.js prototype sinon