Contact Me

Stubs

Are used to isolate and control the input of the code under test during tests.

 A stub is similar to a mock object, but it typically has a more limited scope and is used for a different purpose. A stub is a piece of code that stands in for a real module or function during a test, in order to control the inputs and outputs of the system under test.

 It is also used with mocks to create specific scenarios, such as generally replacing functions that access external services.

 A general rule of thumb is that tests should not rely on external services or the internet (tests should test the logic of the system, not its details).

 So in the case of instability of external systems, it is necessary to create architectural mechanisms to resolve them.


 Here's an example of how to create a stub in javascript using Sinon.js

const myModule = require('./myModule');

const sinon = require('sinon');


const myStub = sinon.stub().returns('stubbed result');


test('myModule uses the stub', () => {

 myModule.doSomething(myStub);

 expect(myStub.calledOnce).toBe(true);

});

 In this example, we are creating a stub called myStub using Sinon's stub() function. The stub returns a hard-coded string 'stubbed result' when it is called. We then call the doSomething() function from myModule and pass in the stub as an argument.

 In contrast to mocks, stubs are less focused on simulating a dependency's behavior and more on controlling the inputs and outputs of the system under test.


Stubs are useful in situations where:

  • you want to isolate a piece of code from its dependencies and control the input it receives during a test
  • you want to test how a piece of code reacts to different inputs
  • you want to test code that triggers callbacks
  • you want to test the order of function calls