Javascript 茉莉花:在使用callFake之后,你怎么能恢复到原来的功能呢?

Javascript 茉莉花:在使用callFake之后,你怎么能恢复到原来的功能呢?,javascript,jasmine,Javascript,Jasmine,假设你有spyOn(obj,'method')。和.callFake(fn)。随后如何将obj.method还原回其原始功能 用例:如果您在每个之前在一个大的中执行callFake,并且希望对其中一个测试用例使用原始方法,但在其余测试用例中使用伪方法 test.js var obj = { method: function () { return 'original'; }, } module.exports = obj; var obj = require(

假设你有
spyOn(obj,'method')。和.callFake(fn)。随后如何将
obj.method
还原回其原始功能

用例:如果您在每个
之前在一个大的
中执行
callFake
,并且希望对其中一个测试用例使用原始方法,但在其余测试用例中使用伪方法

test.js

var obj = {
    method: function () {
        return 'original';
    },
}

module.exports = obj;
var obj = require('../test.js');

describe('obj.method', function () {
    it('should return "original" by default', function () {
    expect(obj.method()).toBe('original');
  });

  it('should return "fake" when faked', function () {
    spyOn(obj, 'method').and.callFake(function () {
      return 'fake';
    });

    expect(obj.method()).toBe('fake');
  });

  it('should return "original" when reverted after being faked', function () {
    spyOn(obj, 'method').and.callFake(function () {
      return 'fake';
    });

    // what code can be written here to get the test to pass?

    expect(obj.method()).toBe('original');
  });
});
testSpec.js

var obj = {
    method: function () {
        return 'original';
    },
}

module.exports = obj;
var obj = require('../test.js');

describe('obj.method', function () {
    it('should return "original" by default', function () {
    expect(obj.method()).toBe('original');
  });

  it('should return "fake" when faked', function () {
    spyOn(obj, 'method').and.callFake(function () {
      return 'fake';
    });

    expect(obj.method()).toBe('fake');
  });

  it('should return "original" when reverted after being faked', function () {
    spyOn(obj, 'method').and.callFake(function () {
      return 'fake';
    });

    // what code can be written here to get the test to pass?

    expect(obj.method()).toBe('original');
  });
});
我使用的是Jasmine v2.5.2


编辑:嗯,我想你可以写:

obj.method = function () {
  return 'original';
};

但那感觉太不干燥了。是否有基于jasmine的东西,如
obj.method.revertToOriginal()

您可以在spied方法上调用
callThrough()
,将其还原为基本函数

var obj={
方法:函数(){
返回“原件”
}
}
描述('obj.method',function()){
它('默认情况下应返回“原始”,函数(){
expect(obj.method()).toBe('original');
});
它('伪造时应返回“假”,函数(){
spyOn(obj,'method')。和.callFake(function(){
返回“假”;
});
expect(obj.method()).toBe('false');
});
它('伪造后还原时应返回“原始”,函数(){
spyOn(obj,'method')。和.callFake(function(){
返回“假”;
});
obj.method.and.callThrough()//还原间谍的方法
expect(obj.method()).toBe('original');
});
});