Book Image

Jasmine JavaScript Testing Update

By : Paulo Vitor Zacharias Ragonha
Book Image

Jasmine JavaScript Testing Update

By: Paulo Vitor Zacharias Ragonha

Overview of this book

Table of Contents (15 chapters)

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...