Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I call the original method inside the supplied function to "andCallFake" of a Jasmine spy?

Tags:

jasmine

I could save the original method in a variable in beforeEach, and then restore it in afterEach, but maybe I can use a spy which will be reset automatically between test suites.

spyOn(Ext, "create").andCallFake(function(className){
    if (className === 'Waf.view.Viewport')
        // call the original Ext.create method
});

Is this possible? I am using Jasmine 1.3

like image 552
SergiuB Avatar asked Dec 19 '22 08:12

SergiuB


2 Answers

You can bind the original method into the fake:

var obj = {
  method: function(name) { return name + '!'; }
}

var methodFake = function(original, name) {
  return 'faked ' + original(name);
}.bind(obj, obj.method)
spyOn(obj, 'method').andCallFake(methodFake);

obj.method('hello') // outputs 'faked hello!'

For what it's worth, I don't think it's great practice to do this, but the need came up for me recently when I was testing some d3 code. Hope it helps.

like image 195
alecmce Avatar answered May 12 '23 03:05

alecmce


This is a hack for Jasmine 2.3. Ideally the fake callback should have access to the reference of the original function to call as needed instead of dancing around like this.

Given that stubbing strategy can be modified on the fly in Jasmine 2.3, the following approach seems to work as well:

var createSpy = spyOn(Ext, "create");
createSpy.and.callFake(function(className){
    if (className === 'Waf.view.Viewport'){
        createSpy.and.callThrough();
        Ext.create(className);        
    }
});
like image 44
Altair7852 Avatar answered May 12 '23 01:05

Altair7852