Sinon - when to use spies / mocks / stubs or just statements?

I am trying to understand how Sinon is used correctly in a node project. I went through examples and documents, but I still do not understand. I set up a directory with the following structure in order to try working through the various Sinon functions and understand where they fit into

|--lib
   |--index.js
|--test
   |--test.js

index.js is an

var myFuncs = {};

myFuncs.func1 = function () {
   myFuncs.func2();
   return 200;
};

myFuncs.func2 = function(data) {
};

module.exports = myFuncs;

test.js starts with the next

var assert = require('assert');
var sinon = require('sinon');
var myFuncs = require('../lib/index.js');

var spyFunc1 = sinon.spy(myFuncs.func1);
var spyFunc2 = sinon.spy(myFuncs.func2);

Admittedly, this is very far-fetched, but in its current form, I would like to verify that any call func1causes a call func2, so I would use

describe('Function 2', function(){
   it('should be called by Function 1', function(){
      myFuncs.func1();
      assert(spyFunc2.calledOnce);
   });
});

I also want to check what func1will return 200so that I can use

describe('Function 1', function(){
   it('should return 200', function(){
      assert.equal(myFuncs.func1(), 200);
   });
});

but I also saw examples in which stubsare used in a similar instance, for example

describe('Function 1', function(){
   it('should return 200', function(){
      var test = sinon.stub().returns(200);
      assert.equal(myFuncs.func1(test), 200);
   });
});

? stub, ?

, , , . , mysql

myFuncs.func3 = function(data, callback) {
   connection.query('SELECT name FROM users WHERE name IN (?)', [data], function(err, rows) {
          if (err) throw err;
          names = _.pluck(rows, 'name');
          return callback(null, names);
       });
    };

, , db , db , . db sinon , , .

+4
1

... .

  • myFunc .

Sinon - . "Mocking" , - , mocks stub. Sinon, . ...

var spyFunc1 = sinon.spy(myFuncs.func1);
var spyFunc2 = sinon.spy(myFuncs.func2);

... . myFuncs.func1 myFuncs.func2 , . , , myFuncs.func1/func2 (: ).

2,1. ('Function 1',...) .

, . , , . , . , , . TDD , , unit test .

2,2. . unit test . func1 .

var test = sinon.stub().returns(200);
assert.equal(myFuncs.func1(test), 200);

100, . , , , , func2 , / ( , HTTP API), .

myFuncs.func2 = sinon.spy();
assert.equal(myFuncs.func1(test), 200);
assert(myFuncs.func2.calledOnce);

, unit test , . func1 , func2. unit test. , :

myFuncs.func1 = sinon.stub().returns(200);
assert.equal(myFuncs.func1(test), 200);

func1 , synon.stub(). return(). , !: D

  1. . . .

3,1. . , . . , : ORM. , before()/beforeEach(), .

3,2. . . (DAL) -. -, DAL. DAL (sinon.mock ) (: db- SQLite , )

  1. . " , ".

, , , . - unit test . , . .

+11

All Articles