Rat*_*tko 30 javascript unit-testing jasmine
我一直在阅读Jasmine文档,我一直在努力理解Spies .and.stub方法实际上做了什么.英语不是我的母语,所以我甚至不知道"存根"这个词实际意味着什么,而且我的语言中没有翻译.
在文档中它说:
当调用策略用于间谍时,可以随时使用and.stub返回原始存根行为.
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);
});
});
Run Code Online (Sandbox Code Playgroud)
什么是and.stub真正做的,它有何作用?
Bor*_*ier 33
对于该术语,您可以查看维基百科:http://en.wikipedia.org/wiki/Test_stub
简而言之,它是一个"假"对象,您可以控制它替换代码中的"真实"对象.
对于这个功能,我理解的是and.stub()消除了and.callThrough()对间谍的影响.
当你调用时and.callThrough,间谍充当代理,调用真正的函数,但是通过间谍对象允许你添加测试,如期望.
当你打电话and.stub或者你从不打电话时and.callThrough,间谍不会调用真正的功能.当你不想测试对象的行为时,它确实非常有用,但要确保它被调用.帮助您保持测试真正统一.
pan*_*say 11
要完成上一个答案:
实际上,从文档中不清楚,但在源代码中非常清楚:
plan = function() {};
Run Code Online (Sandbox Code Playgroud)
- >被调用的函数为空
this.callThrough = function() {
plan = originalFn;
Run Code Online (Sandbox Code Playgroud)
- >被调用的函数是原始函数
this.stub = function(fn) {
plan = function() {};
Run Code Online (Sandbox Code Playgroud)
- >被调用的函数为空(再次)