How to use the spy function from sinon

Find comprehensive JavaScript sinon.spy code examples handpicked from public code repositorys.

sinon.spy is a JavaScript function that creates a "spy" function, which can record information about how it was called and its return value.

1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
});

it('should inherit from Node OutogingMessage.end()');

it('triggers callback provided as 1st argument', function() {
  var callback = sinon.spy();
  response.end(callback);
  
  expect(callback).to.have.been.called;
});
fork icon130
star icon697
watch icon18

+ 74 other calls in file

76
77
78
79
80
81
82
83
84
describe('#addProcessor', () => {
  let processor;

  beforeEach(() => {
    global.OffscreenCanvas = OffscreenCanvas;
    processor = { processFrame: sinon.spy() };
    videoTrack._dummyEl = 'foo';
    log.warn = sinon.spy();
  });
fork icon208
star icon537
watch icon83

+ 23 other calls in file

How does sinon.spy work?

sinon.spy works by creating a "spy" function that can be used to record information about its invocation and behavior. The spy function can be used like any other function in your code, but it also provides a number of additional features for testing and debugging, including: Recording how many times the function was called, with what arguments, and in what order. Recording the return value of the function and any exceptions thrown. Overriding the behavior of the function to return a specified value or throw a specified exception. Accessing the "this" object of the function when it was called. By using sinon.spy, you can easily test how your functions are being called and interacted with by other parts of your code, without having to modify the functions themselves. This makes it a powerful tool for unit testing, debugging, and development in general.

1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
let funcStub;
let logSpy;
const ports = [16127, 16126, 16129, 80, 443, 16125, 11, 13];
beforeEach(() => {
  utilStub = sinon.stub(util, 'promisify');
  logSpy = sinon.spy(log, 'info');
});

afterEach(() => {
  sinon.restore();
fork icon227
star icon164
watch icon24

223
224
225
226
227
228
229
230
231
232
db = mocks.mockDB({
  uid: UID,
  email: TEST_EMAIL,
  locale: ACCOUNT_LOCALE,
});
db.createAccountSubscription = sinon.spy(async (data) => ({}));
db.deleteAccountSubscription = sinon.spy(
  async (uid, subscriptionId) => ({})
);
db.cancelAccountSubscription = sinon.spy(async () => ({}));
fork icon206
star icon482
watch icon43

+ 11 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const sinon = require("sinon");

// Create a spy function using sinon.spy
const myFunction = sinon.spy();

// Call the spy function multiple times
myFunction(1, 2, 3);
myFunction("hello");
myFunction();

// Check the number of times the spy function was called
console.log(myFunction.callCount);

// Check the arguments passed to the spy function
console.log(myFunction.firstCall.args);
console.log(myFunction.secondCall.args);

// Override the behavior of the spy function to return a specific value
myFunction.returns("world");

// Call the spy function again and check its return value
console.log(myFunction("test"));

In this example, we use sinon.spy to create a spy function called myFunction. We then call the myFunction function multiple times with different arguments. We use the callCount property of the myFunction object to check how many times it was called, and the args property to check the arguments passed to the first and second calls. We then use the returns method of the myFunction object to override its behavior and make it return the string 'world'. Finally, we call myFunction again and log its return value to the console. By using sinon.spy, we can easily test the behavior of our functions and get detailed information about how they are being called, making it a powerful tool for unit testing and debugging.

177
178
179
180
181
182
183
184
185
186
187
    },
    async get(key) {
      return _data[key];
    },
  };
  Object.keys(mock).forEach((key) => sinon.spy(mock, key));
  return mock;
}


mockConfig.redis = mockRedisConfig;
fork icon206
star icon482
watch icon43

39
40
41
42
43
44
45
46
47
48
config.publicUrl = 'https://public.url';

const log = options.log || mocks.mockLog();
const db = options.db || mocks.mockDB();
const oauth = options.oauth || {
  getRefreshTokensByUid: sinon.spy(async () => []),
};
const customs = options.customs || {
  check: function () {
    return Promise.resolve(true);
fork icon206
star icon481
watch icon43

+ 59 other calls in file

66
67
68
69
70
71
72
73
74
75
76
77
      body: '{"Granule Not Found"}',
    });
  },
};


const pMapSpy = sinon.spy(pMap);


// Import the discover-granules functions that we'll be testing, configuring them to use the fake
// granules module and the fake logger.
const {
fork icon102
star icon224
watch icon24

+ 2 other calls in file

6110
6111
6112
6113
6114
6115
6116
6117
6118
6119

after(function () {
	nock.cleanAll();
});

var getToken = sinon.spy(function any(callback) {
	callback({ accessToken: "token001" });
});

it("sends the request to the right end point and returns a response", function (done) {
fork icon49
star icon221
watch icon28

723
724
725
726
727
728
729
730
731
});


describe('#_emitEvent(eventType, payload)', () => {
    it('should emit Event:on(canceled)', () => {
        const spy = sinon.spy();

        const task = new Task(worker, new Request(config), reservationSid, pendingTaskDescriptor);
        assert.equal(task.status, 'reserved');
fork icon27
star icon20
watch icon20

+ 14 other calls in file

62
63
64
65
66
67
68
69
70
71
describe('whenReady', () => {
    it('should call the callback function after the backoff interval', async() => {
        const intervalCount = 2;
        const expectedDelay = 1500;
        sinon.stub(retryUtil, 'generateBackoffInterval').returns(expectedDelay);
        const spy = sinon.spy(global, 'setTimeout');
        const callback = sinon.spy();
        await retryUtil.whenReady(intervalCount).then(callback);
        expect(spy.calledWith(sinon.match.any, expectedDelay)).to.be.true;
        expect(callback.called).to.be.true;
fork icon27
star icon20
watch icon20

+ 5 other calls in file

23
24
25
26
27
28
29
30
31
let signaling;
let supervisor;

const Request = () => {
  request = createEmitterStub(require('../../../lib/util/Request').default);
  request.post = sinon.spy(() => Promise.resolve());
  request.get = sinon.spy(() => Promise.resolve());
  return request;
};
fork icon27
star icon20
watch icon20

+ 11 other calls in file

11
12
13
14
15
16
17
18
19
20
describe("model/twitter", function() {
  let oldGetFunction;
  before(function (bddone) {
    config.initialise();
    oldGetFunction = twitter.for_debug_only.twitterClient.get;
    twitter.for_debug_only.twitterClient.get = sinon.spy(function (param, option, cb) {
      should(option).eql({ tweet_mode: "extended" });
      if (param.substring(0, 15) === "/statuses/show/") {
        const id = param.substring(15, 999);
        let r = fs.readFileSync(path.join(__dirname, "data", "TwitterStatus-" + id + ".json"));
fork icon10
star icon27
watch icon6

+ 9 other calls in file

241
242
243
244
245
246
247
248
249
// Arrange:
const throttlingConfig = {
	burst: 20,
	rate: 5
};
const spy = sinon.spy(restify.plugins, 'throttle');

// Act:
bootstrapper.createServer({ protocol: 'HTTP' }, createFormatters(), throttlingConfig);
fork icon23
star icon26
watch icon17

+ 41 other calls in file

264
265
266
267
268
269
270
271
272
});

it('should call listeners on a "disconnect" event', () => {
  const cb = sinon.stub();

  sinon.spy(websocket, "clear");
  websocket.retrying = false;
  websocket.addListener("disconnect", cb);
  should(websocket.listeners("disconnect").length).be.eql(1);
fork icon17
star icon41
watch icon17

50
51
52
53
54
55
56
57
58
59
  },
  flash: sinon.spy()
}
res = {
  setHeader: sinon.stub(),
  status: sinon.spy(),
  redirect: sinon.spy(),
  render: sinon.spy(),
  locals: {
    stripeAccount: {
fork icon13
star icon19
watch icon18

+ 18 other calls in file

100
101
102
103
104
105
106
107
108
109
    }
  }
  next = sinon.spy()
  setStripeAccountSetupFlagMock = sinon.spy(() => Promise.resolve())
  createDirectorMock = sinon.spy(() => Promise.resolve())
  updateDirectorMock = sinon.spy(() => Promise.resolve())
  updateCompanyMock = sinon.spy(() => Promise.resolve())
  listPersonsMock = sinon.spy(() => Promise.resolve())
  completeKycMock = sinon.spy(() => Promise.resolve())
})
fork icon13
star icon19
watch icon18

+ 18 other calls in file

15
16
17
18
19
20
21
22
23
24
let req
let res
let next

const setStripeAccountSetupFlagMock = sinon.spy(() => Promise.resolve())
const loggerInfoMock = sinon.spy(() => Promise.resolve())
const stripeAcountId = 'acct_123example123'

function getControllerWithMocks () {
  return proxyquire('./post.controller', {
fork icon13
star icon19
watch icon18

+ 6 other calls in file

49
50
51
52
53
54
55
56
57
58
  }
  next = sinon.spy()
})

it('should call stripe and connector and redirect to add psp account details redirect route', async () => {
  updateBankAccountMock = sinon.spy(() => Promise.resolve())
  setStripeAccountSetupFlagMock = sinon.spy(() => Promise.resolve())
  const controller = getControllerWithMocks()

  await controller(req, res, next)
fork icon13
star icon19
watch icon18

+ 22 other calls in file

82
83
84
85
86
87
88
89
90
91
92
93


describe('organisation address - post controller', () => {
  let req, res, next, controller
  let responseData


  const mockUpdateService = sinon.spy(() => {
    return new Promise(resolve => {
      resolve(updatedService)
    })
  })
fork icon13
star icon18
watch icon18

+ 98 other calls in file

47
48
49
50
51
52
53
54
55
56
    requests.push(req);
  };

  sinon.spy(console, 'log');
  sinon.spy(console, 'info');
  sinon.spy(console, 'warn');
  sinon.spy(console, 'error');
});

afterEach(function() {
fork icon80
star icon0
watch icon1

+ 7 other calls in file