Javascript Testing with Jasmine Reply

Rick HerrmannOne of the features I like about Jasmine is that the ability to mock objects and do interaction based testing is built into the tool.  When testing C# code (with NUnit, MSTest, or even NSpec) you have to pull in another tool to handle mocking.

In Jasmine, mock objects are called spies.  Accordingly, there is a built-in function called spyOn, which takes two parameters:

  1. A reference to the object with the function to be “spied on”
  2. A string with the name of the function to mock

For example, lets say you have an object called validator with a function called showValidationMessage.  You want to test that given a certain set of inputs, the validation message will be displayed.  The test might look something like this:

   1:  describe('validation specs', function() {
   2:      var validator;
   3:      var firstName, lastName;
   4:      beforeEach(function() {
   5:          validator = new Example.Validator();
   6:      });
   7:  
   8:      describe('when the first or last name are not entered', function() {
   9:          beforeEach(function() {
  10:              spyOn(validator, 'showValidationMessage');
  11:              firstName = 'Homer';
  12:              lastName = '';
  13:              validator.validateInputs(firstName, lastName);
  14:          });
  15:  
  16:          it('then the validation message should be displayed', function() {
  17:              expect(validator.showValidationMessage).toHaveBeenCalled();
  18:          })
  19:      });
  20:  });

On line 10 we use the Jasmine spyOn function to mock the showValidationMessage method on the validator object. Then on line 17 we can use the toHaveBeenCalled Jasmine matcher to verify that the mocked method has been called. If the showValidationMessage method is not called, then this test will fail.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s