development:testing:sinonjs:start

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
development:testing:sinonjs:start [2019/01/13 12:36] – created don.leedevelopment:testing:sinonjs:start [2019/01/13 13:05] (current) don.lee
Line 1: Line 1:
 ====== Sinon JS ====== ====== Sinon JS ======
  
 +If your test will also involve other 3rd party library, etc. multer. You better also check their own test cases for reference. e.g. https://github.com/expressjs/multer/tree/master/test
  
 +===== Reference =====
 +
 +  * https://sinonjs.org/
   * https://semaphoreci.com/community/tutorials/best-practices-for-spies-stubs-and-mocks-in-sinon-js   * https://semaphoreci.com/community/tutorials/best-practices-for-spies-stubs-and-mocks-in-sinon-js
   * https://codeutopia.net/blog/2016/05/23/sinon-js-quick-tip-how-to-stubmock-complex-objects-such-as-dom-objects/   * https://codeutopia.net/blog/2016/05/23/sinon-js-quick-tip-how-to-stubmock-complex-objects-such-as-dom-objects/
Line 7: Line 11:
 ===== Spy ===== ===== Spy =====
  
-Check if a method is called+  * Check if a method is called
  
 <code> <code>
Line 16: Line 20:
 </code> </code>
  
 +===== Stub =====
 +
 +  * Replace existing method with stub to avoid actually execute the method
 +
 +==== Method 1 ====
 +
 +  * define a fake function so that it will call that fake one when call
 +
 +<code>
 +function fake() {  // a fake function to be called
 +}
 +
 +const stub = sinon.stub(object, 'method').callFakes(fake) // you could also replace the fake with another real function
 +...
 +stub.restore() // remove stub
 +expect(stub.callCount).to.be.eql(n) // check if the method is call n times
 +</code>
 +
 +==== Method 2 ====
 +
 +  * define a return value no matter how you call the stub
 +
 +<code>
 +const stub = sinon.stub(object, 'method').returns(val) // always return same val
 +...
 +const test = stub()
 +expect(test).to.be.eql(val)
 +stub.restore() // remove stub
 +expect(stub.callCount).to.be.eql(n) // check if the method is call n times
 +</code>
 +
 +==== Method 3 ====
 +
 +  * resolve a promise with same value no matter how you call the stub
 +
 +<code>
 +const stub = sinon.stub(object, 'method').resolve(val) // always resolve same val
 +...
 +const test = await stub()
 +expect(test).to.be.eql(val)
 +stub.restore() // remove stub
 +expect(stub.callCount).to.be.eql(n) // check if the method is call n times
 +</code>
  
  • development/testing/sinonjs/start.1547354212.txt.gz
  • Last modified: 2019/01/13 12:36
  • by don.lee