javascript Jasmine Spies.and.stub 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28008796/
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 Spies.and.stub method
提问by Ratko
I've been reading through the Jasmine documentation and I've been struggling to understand what the Spies .and.stub
method actually does. English is not my native language, so I don't even know what the word "stub" actually means, and there is no translation for it in my language.
我一直在阅读 Jasmine 文档,并且一直在努力理解 Spies.and.stub
方法的实际作用。英语不是我的母语,所以我什至不知道“stub”这个词的实际含义,而且在我的语言中也没有翻译。
In the documentation it says:
在文档中它说:
When a calling strategy is used for a spy, the original stubbing behavior can be returned at any time with and.stub.
当一个spy使用调用策略时,可以随时用and.stub返回原来的stubbing行为。
describe("A spy", function() {
var foo, bar = null;
beforeEach(function() {
foo = {
setBar: function(value) {
bar = value;
}
};
spyOn(foo, 'setBar').and.callThrough();
});
it("can call through and then stub in the same spec", function() {
foo.setBar(123);
expect(bar).toEqual(123);
foo.setBar.and.stub();
bar = null;
foo.setBar(123);
expect(bar).toBe(null);
});
});
What does and.stub
actually do and how is it useful?
它and.stub
实际上做了什么以及它有什么用?
回答by Boris Charpentier
For the term, you can look at wikipedia : http://en.wikipedia.org/wiki/Test_stub
对于该术语,您可以查看维基百科:http: //en.wikipedia.org/wiki/Test_stub
In a nutshell it's a "fake" object that you can control that replaces a "real" object in your code.
简而言之,它是一个“假”对象,您可以控制它来替换代码中的“真实”对象。
For the function, what I understand is that and.stub()
removes the effect of and.callThrough()
on a spy.
对于该功能,我的理解是and.stub()
消除了and.callThrough()
对间谍的影响。
When you call and.callThrough
, the spy acts as a proxy, calling the real function, but passing through a spy object allowing you to add tests like expectation.
当您调用 时and.callThrough
,spy 充当代理,调用真正的函数,但通过一个 spy 对象允许您添加诸如期望之类的测试。
When you call and.stub
, or if you never call and.callThrough
, the spy won't call the real function. It's really usefull when you don't want to test an object's behavior, but be sure that it was called. Helping you to keep your test truly unitary.
当您调用and.stub
,或者如果您从不调用and.callThrough
,间谍将不会调用真正的函数。当您不想测试对象的行为但要确保它被调用时,它真的很有用。帮助您保持测试真正的统一。
回答by pansay
To complete the previous answer:
要完成上一个答案:
Indeed, it's not clear from the doc, but it's very clear in the source code:
确实,从文档中并不清楚,但在源代码中非常清楚:
plan = function() {};
-> the called function is empty
-> 被调用的函数为空
this.callThrough = function() {
plan = originalFn;
-> the called function is the original function
-> 被调用的函数是原函数
this.stub = function(fn) {
plan = function() {};
-> the called function is empty (again)
-> 被调用的函数是空的(再次)