Spying on an object's functions

A spy, by itself is very useful, but its true power comes with changing an object's original implementation using a counterpart spy.

Consider the following example, which is aimed at validating that when the form is submitted, the create function of view has to be called:

describe("NewInvestmentView", function() {
  var view;

  // setup and other specs ...

  describe("with its inputs correctly filled", function() {

    // setup and other specs ...

    describe("and when the form is submitted", function() {
      beforeEach(function() {
        spyOn(view, 'create'),
        view.$element.submit();
      });

      it("should create an investment", function() {
        expect(view.create).toHaveBeenCalled();
      });
    });
  });
});

Here, we make use of the global Jasmine function spyOn to change the create function of view with a spy.

Then, later in the spec, we use the toHaveBeenCalled Jasmine matcher to validate that the view.create function was called.

After the spec is done, Jasmine restores the object's original behavior.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset