2017-01-08 1 views
1

spyOn(obj, 'method').and.callFake(fn);이라고 말하십시오. 어떻게하면 obj.method을 다시 원래의 기능으로 되돌릴 수 있습니까?Jasmine : callFake 사용 후 어떻게 원래 함수로 되돌릴 수 있습니까?

사용 사례 : 이 큰 경우 beforeEach이고 테스트 케이스 중 하나에 원래 방법을 사용하고 나머지는 가짜 인 경우가 있습니다.

test.js

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

module.exports = obj; 

내가 재스민 v2.5.2을 사용하고 testSpec.js

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

.


편집 : 글쎄, 난 그냥 쓸 수있는 가정 :

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

을하지만 그건 너무하지-DRY 느낀다. 재 스민을 기반으로하는 뭔가가 obj.method.revertToOriginal()과 같은가요?

답변

1

스파이 방법으로 callThrough()으로 전화를 걸어 기본 기능으로 되돌릴 수 있습니다.

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

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

 
    obj.method.and.callThrough() // method for revert spy 
 

 
    expect(obj.method()).toBe('original'); 
 
    }); 
 
});
<link href="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine.css" rel="stylesheet" /> 
 
<script src="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine-2.0.3-concated.js"></script>

관련 문제