Javascript Has Spies

Spies vs Mocks vs Stubs?

We are covering testing frameworks at PCS this week, particularly Jasmine and Sinon.

Jasmine has a similar structure to RSpec:

describe("Class to describe", function() {
  it("should have some behavior". function() {
    //assertions
  });
});

Also similar to RSpec, Jasmine allows you to spy on behavior. Using spies, I can watch a method call and collect information about it.

  • Want to know if it was called?
expect(method).toHaveBeenCalled()
  • Want to know how many times?
expect(method.callCount).toEqual(3)
  • Want to know how it was called?
expect(method).toHaveBeenCalledWith(args)

For example:

describe( "Spy on methods", function () {
  it( "should watch calls to console", function () {
    var mySpy = spyOn(console, "log");
    console.log("test1");
    console.log("test2");
    console.log("test3");

    expect(mySpy.callCount).toEqual(3);
  });
});

Tomorrow, I conquer Stubs and Mocks!