javascript Jasmine 有 createSpy() 返回模拟对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27680933/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jasmine have createSpy() return mock object
提问by ritmatter
I'm trying to mock up a response object, and it looks something like this:
我正在尝试模拟一个响应对象,它看起来像这样:
var res = {
status: jasmine.createSpy().andReturn(this),
send: jasmine.createSpy().andReturn(this)
}
This returns the jasmine object. I'd really like to return the original res variable containing the mocked functions. Is that possible? I'm mainly implementing this to unit test functions containing res.status().send(), which is proving to be difficult.
这将返回茉莉花对象。我真的很想返回包含模拟函数的原始 res 变量。那可能吗?我主要是在包含 res.status().send() 的单元测试函数中实现这一点,事实证明这很困难。
回答by ritmatter
The answer here is actually pretty quick. Calling andReturn() will give you jasmine as 'this'. But, if you write andCallFake(), that function considers the mocked object to be this. Solution looks like so:
这里的答案实际上很快。调用 andReturn() 会给你 jasmine 作为 'this'。但是,如果您编写 andCallFake(),该函数会将模拟对象视为 this。解决方案如下所示:
status: jasmine.createSpy().and.callFake(function(msg) { return this });
回答by Olivier Torres
this works for me:
这对我有用:
const res = {
status: jasmine.createSpy('status').and.callFake(() => res),
send: jasmine.createSpy('send').and.callFake(() => res),
};