Friday 2 December 2016

Spying on Jasmine vs Mocha + Sinon + Chai


                           Spying on Jasmine vs Mocha + Sinon  + Chai


As a UI front end developer, many of us have come across the Jasmine framework for Js test cases and Mocha Sinon with Chai assertion Library.  We know that it almost impossible to write test case without SPY functionality of any Testing Framework. Let me tell you basic difference between above two framework when you make a SPY for test case.


1. Anonymous spy : 

creates an anonymous function that records arguments, this value, exceptions and return values for all calls. It does not call actual function.

Using Jasmine:


           object.method =  jasmine.createSpy(); OR

            spyOn( object, 'method' ); (from jasmine 2.0) 

*Important : SpyOn needs method to be present on object so not actually anonymous spy while jasmnie.createSpy does not require as it assigns empty anonymous function. 

In short if your try spyOn(object, 'method') without having method available on object then you will get error stating the method to be spied upon does not exist on object.

Using Mocha chai:  


     object.method =  sinon.spy();
            
             sinon.stub( object , 'method');

*Important :  sinon.stun needs  method to be present on object so not actually anonymous spy while sinon.spy() does not require as it assigns empty anonymous function.



2. Spy with Actual function call : 

calls actual implementation and allow to record arguments, this value, exceptions and return values for all calls. 

Using Jasmine:


              spyOn( object, 'method' ).add.callThrough()

Using Mocha chai:


             sinon.spy(object , 'method');   

             (Notice the difference between sinon.spy and sinon.stub)



3. Spy with stub function call : 

assign the stub function which can receive the arguments and can return the stub data. 


Using Jasmine:


      spyOn( object, 'method' ).add.callFake( function (args) { 
                  return  value;
             });            

             for just return the value :

              spyOn( object, 'method' ).add.returnValue(true);



Using Mocha chai: 


      sinon.stub( object, 'method', function (args) {
                   retrun value;
              }); 



conclusion:


I write the test cases in both framework and above noticed 
differences helped me a lot to quick writing of the test case. Hope you can get benefit of that. Enjoy :)

1 comment: