Contact Me

Spies

Are used to observe and record the behavior of a piece of code during a test.

 A spy is another type of test double that can be used to observe and record the behavior of a piece of code during a test. Spies are similar to stubs in that they can be used to replace a real function or module during a test, but they also record information about how the function or module is called and what it returns.

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

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

const sinon = require('sinon');


const mySpy = sinon.spy();


test('myModule calls the spy', () => {

 myModule.doSomething(mySpy);

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

});

 In this example, we are creating a spy called mySpy using Sinon's spy() function. We then call the doSomething() function from myModule and pass in the spy as an argument. The spy records information about the call, such as the arguments that were passed in and the value that was returned.

 We can then make assertions about the behavior of the code under test by checking the properties of the spy object, such as whether it was called or how many times it was called.


Spies are useful in situations where:

  • you want to observe the behavior of a function or module during a test without affecting its output
  • you want to test how a function or module is called and what arguments it is called with
  • you want to test the number of times a function or module is called
  • you want to test whether a function or module is called at all