我可以将提供的函数中的原始方法调用到" andCallFake"茉莉花间谍?

时间:2014-12-10 10:22:09

标签: jasmine

我可以将原始方法保存在beforeEach中的变量中,然后在afterEach中恢复它,但也许我可以使用一个间谍,它会在测试套件之间自动重置。

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

这可能吗?我正在使用Jasmine 1.3

5 个答案:

答案 0 :(得分:5)

这是Jasmine 2.3的黑客攻击。理想情况下,假回调应该可以访问原始函数的引用,以便根据需要调用而不是像这样跳舞。

鉴于在Jasmine 2.3中可以修改存根策略on the fly,以下方法似乎也可以使用:

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

答案 1 :(得分:4)

您可以将原始方法绑定到假冒:

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!'

对于它的价值,我认为这样做并不是很好的做法,但是最近我在测试一些d3代码时出现了需求。希望它有所帮助。

答案 2 :(得分:0)

这是我如何使用Jasmine和Angular Service来实现的。我正在监视的服务正在测试服务的构造函数中调用:

// create the TestBed:
TestBed.configureTestingModule({
    providers: [MyInjectedService, ServiceConstructorInjectedService]
});
myInjectedService = TestBed.get(MyInjectedService);
serviceConstructorInjectedService = TestBed.get(ServiceConstructorInjectedService);

it('should...', () => {
    let returnValue = 'return this';
    spyOn(serviceConstructorInjectedService , 'myFunction').and.callFake((param) => {
        if (param === 'testValue') {
            return returnValue;
        } else {
            return ServiceConstructorInjectedService.prototype.myFunction(param);
        }
    });
});

// instantiate the service again so spy is called
myInjectedService = new MyInjectedService(
    TestBed.get(ServiceConstructorInjectedService)
);

答案 3 :(得分:-1)

我最终做了这样的事情:

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

答案 4 :(得分:-1)

应该相互独立地测试不同的场景。尝试将测试结构化为类似的东西。

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
    });
});