简体   繁体   English

Jasmine中and.stub与and.callFake有什么区别

[英]What is the difference between and.stub vs and.callFake in Jasmine

I am a newbie to Jasmine and a bit confused between above two functions. 我是Jasmine的新手,在上述两个功能之间有些困惑。 My sole purpose is to give a fake implementation to a spy function. 我唯一的目的是为间谍函数提供伪造的实现。 But, If I put debugger in callFake the it is getting called but and.stub 's function is not getting called. 但是,如果我将调试器放入callFake ,它将被调用,但是and.stub的函数未被调用。 Could anyone please explain what is the difference between these two functions. 谁能解释这两个功能之间的区别。

spyOn(manager, 'getUsers').and.stub(function () {
    //to do
});

vs

 spyOn(manager, 'getUsers').and.callFake(function () {
        //to do
    });

Looking at the documentation located at https://jasmine.github.io/2.0/introduction.html#section-Spies , when you spyOn something it logs of all the calls being made on the spied on object method. 查看位于https://jasmine.github.io/2.0/introduction.html#section-Spies的文档,当您spyOn某些东西时,它会记录所有在spyOn对象方法上进行的调用。 This means that it is calling the actual method of the object, but keeping track of what calls were made. 这意味着它正在调用对象的实际方法,但要跟踪进行了什么调用。

If you want to allow using the original object, but don't want specific methods to be called, you have the options of using and.callFake and and.stub . 如果要允许使用原始对象,但又不想调用特定的方法,则可以选择使用and.callFakeand.stub The differences are in the method signatures. 区别在于方法签名。


callFake takes a function as a parameter. callFake将函数作为参数。 This allows you to fake the method call and return a value of your desire. 这使您可以伪造方法调用并返回所需的值。

original method signature is myMethod(param1: string): string 原始方法签名为myMethod(param1: string): string

spyOn(service, 'myMethod').and.callFake((param1) => {
    expect(param1).toBe('value');
    return 'returnValue';
});

stub has no parameters and merely intercepts the call to the method stub没有参数,仅拦截对方法的调用

spyOn(service, 'myMethod').and.stub();

myMethod can have parameters and can have a return type, but it doesn't matter since stub just intercepts the call and will return null if there is a return type. myMethod可以具有参数并且可以具有返回类型,但这并不重要,因为存根仅截获该调用,如果存在返回类型,则返回null


In both instances, the method calls are logged and you can then do something like expect(service.myMethod).toHaveBeenCalled() or expect(service.myMethod).toHaveBeenCalledWith('value') 在这两种情况下,都会记录方法调用,然后您可以执行诸如expect(service.myMethod).toHaveBeenCalled()expect(service.myMethod).toHaveBeenCalledWith('value')

Possible duplicate of What's the difference between faking, mocking, and stubbing? 伪造,嘲笑和存根之间的区别什么? .

There you'll find a concise answer with all the differences. 在那里,您会找到所有差异的简明答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM