तो जासूस चश्मा के बीच स्वचालित रूप से रीसेट कर रहे हैं।
यदि आप एक beforeEach()
भीतर andCallFake()
उपयोग करना और फिर जबरन एक कल्पना के भीतर इसे बदलने के लिए (जो की संभावना है कारण है कि यह ऐसा करने से रोकने की कोशिश करता है) प्रयास आप वास्तव में मूल कार्य के "बहाली" के लाभ नहीं मिलता है ।
तो सावधान रहना, अपने जासूस ऐसे jQuery के रूप में एक वैश्विक वस्तु पर स्थापित किया जा रहा है, खासकर अगर।
प्रदर्शन:
var a = {b:function() { return 'default'; } }; // global scope (i.e. jQuery)
var originalValue = a.b;
describe("SpyOn test", function(){
it('should return spy1', function(){
spyOn(a, 'b').andCallFake(function(params) {
return 'spy1';
})
expect(a.b()).toEqual('spy1');
});
it('should return default because removeAllSpies() happens in teardown', function(){
expect(a.b()).toEqual('default');
});
it('will change internal state by "forcing" a spy to be set twice, overwriting the originalValue', function(){
expect(a.b()).toEqual('default');
spyOn(a, 'b').andCallFake(function(params) {
return 'spy2';
})
expect(a.b()).toEqual('spy2');
// This forces the overwrite of the internal state
a.b.isSpy = false;
spyOn(a, 'b').andCallFake(function(params) {
return 'spy3';
})
expect(a.b()).toEqual('spy3');
});
it('should return default but will not', function(){
expect(a.b()).toEqual('default'); // FAIL
// What's happening internally?
expect(this.spies_.length).toBe(1);
expect(this.spies_[0].originalValue).toBe(originalValue); // FAIL
});
});
describe("SpyOn with beforeEach test", function(){
beforeEach(function(){
spyOn(a, 'b').andCallFake(function(params) {
return 'spy1';
})
})
it('should return spy1', function(){
// inspect the internal tracking of spies:
expect(this.spies_.length).toBe(1);
expect(this.spies_[0].originalValue).toBe(originalValue);
expect(a.b()).toEqual('spy1');
});
it('should return spy2 when forced', function(){
// inspect the internal tracking of spies:
expect(this.spies_.length).toBe(1);
expect(this.spies_[0].originalValue).toBe(originalValue);
// THIS EFFECTIVELY changes the "originalState" from what it was before the beforeEach to what it is now.
a.b.isSpy = false;
spyOn(a, 'b').andCallFake(function(params) {
return 'spy2';
})
expect(a.b()).toEqual('spy2');
});
it('should again return spy1 - but we have overwritten the original state, and can never return to it', function(){
// inspect the internal tracking of spies:
expect(this.spies_.length).toBe(1);
expect(this.spies_[0].originalValue).toBe(originalValue); // FAILS!
expect(a.b()).toEqual('spy1');
});
});
// If you were hoping jasmine would cleanup your mess even after the spec is completed...
console.log(a.b == originalValue) // FALSE as you've already altered the global object!
निश्चित रूप से आपने सही "सही" उत्तर चुना है? – hgoebl
जैस्मीन 2.0 के रूप में ["एक जासूस केवल 'वर्णन' या 'यह' ब्लॉक में मौजूद है जिसमें इसे परिभाषित किया गया है, और प्रत्येक spec के बाद हटा दिया जाएगा।"] (Https://jasmine.github.io/2.0/ परिचय.html # सेक्शन-जासूस) – AJP