Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Broadly, I agree with Dave Newton's answer above. However, there are some edge-cases to this approach that you should consider.</p> <p>Take a variation to Dave's solution, with another test-case:</p> <pre><code>// production code var Klass = function() { this.call_count = 0; this.called_method(); }; Klass.prototype.called_method = function() { ++this.call_count; }; // test code describe("The Klass constructor", function() { it("should call its prototype's called_method", function() { spyOn(Klass.prototype, 'called_method'); var k = new Klass(); expect(k.called_method).toHaveBeenCalled(); }); it('some other test', function() { var k = new Klass(); expect(k.call_count).toEqual(1); }); }); </code></pre> <p>The second test will fail because the spy setup in the first test persists across the test boundaries into the second method; called_method doesn't increment call_count, so this.call_count does not equal 1. It's also possible to come up with scenarios with false positives - tests that pass, that shouldn't.</p> <p>On top of this, because the spy remains, the more Klass instances that are created, the bigger the memory heap the spy will consume, because the spy will record each call to called_method. This probably isn't a problem in most circumstances, but you should be aware of it, just in case.</p> <p>A simple solution to this problem would be to make sure that the spy is removed after it has been used. It can look a bit ugly, but something like this works:</p> <pre><code>// test code describe("The Klass constructor", function() { it("should call its prototype's called_method", function() { var spy = jasmine.createSpy('called_method'); var method = Klass.prototype.called_method; Klass.prototype.called_method = spy; var k = new Klass(); expect(spy).toHaveBeenCalled(); Klass.prototype.called_method = method; }); </code></pre> <p>[NOTE - a little opinion to finish] A better solution would be to change the way you write production code to make the code easier to test. As a rule, spying on prototypes is probably a code-smell to be avoided. Instead of instantiating dependencies in the constructor, inject them. Instead of doing initialization in the constructor, defer to an appropriate init method.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload