Can I call the original method inside the supplied function on the "Jasmine spy andCallFake"?

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

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

Is it possible? I am using Jasmine 1.3

+4
source share
4 answers

You can associate the original method with a 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 was a great practice, but lately it occurred to me that I was testing some d3 code. Hope this helps.

+4
source

2.3. , , .

, Jasmine 2.3, , :

var createSpy = spyOn(Ext, "create");
createSpy.and.callFake(function(className){
    if (className === 'Waf.view.Viewport'){
        createSpy.and.callThrough();
        Ext.create(className);        
    }
});
+4

I ended up doing something like this:

var origFunc = Ext.create;
spyOn(Ext, "create").andCallFake(function(className, classConfig){
    if (className === 'Waf.view.Viewport') {
         return {};
    } else {
         return origFunc.apply(null, arguments);
    }
});
-1
source

Different scenarios should be checked independently of each other. Try structuring your tests for something like this.

beforeEach(function () {
    spyOn(Ext, 'create');
});

describe('scenario 1', function () {
    beforeEach(function () {
        Ext.create.andCallThrough();
    });

    it('should do something', function () {
        // do your assertions
    });
});

describe('scenario 2', function () {
    beforeEach(function () {
        Ext.create.andCallFake(function () {
            // faked function
        });
        // or if you're always returning a constant value, use andReturn
        // Ext.create.andReturn({});
    });

    it('should do something', function () {
        // do your assertions
    });
});
-1
source

All Articles