How to use the stub function from sinon

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

sinon.stub creates a new stub function with optional behavior to replace an existing function or object property.

11
12
13
14
15
16
17
18
19
20

describe('myAPI.hello method', function () {

    beforeEach(function () {
        // stub out the `hello` method
        sandbox.stub(myAPI, 'hello');
    });

    afterEach(function () {
        // completely restore all fakes created through the sandbox
fork icon810
star icon1
watch icon3

28
29
30
31
32
33
34
35
36
37
requestEventsData,
dayjs: dayjs.utc,
dav: {
  ns: namespace,
  request: {
    propfind: sinon.stub(),
    syncCollection: sinon.stub(),
  },
  Request: sinon.stub().returns({ requestDate: 'request3' }),
},
fork icon264
star icon0
watch icon0

+ 31 other calls in file

How does sinon.stub work?

sinon.stub is a function provided by Sinon.js library which creates a new function that can replace an existing function during tests, allowing you to control the behavior of the replaced function and assert how it is used. It can be used to stub out dependencies or API calls to isolate your code under test. When the stub function is called, it can be configured to return a specific value, throw an error, or call a separate function.

45
46
47
48
49
50
51
52
53
54
55


describe('Fetchr Server API Test', () => {
    describe('success tests', () => {
        beforeAll(() => {
            sinon.stub(CLIENTS, 'load').returns(Promise.resolve());
            sinon.stub(CLIENTS, 'middleware').returns((req, res, next) => {
                req.clients = {
                    zms: {
                        putAssertion: (params, callback) =>
                            params.forcefail
fork icon252
star icon757
watch icon51

5
6
7
8
9
10
11
12
13
14
15
16
17
const helper = require('../../src/helpers/helper');


describe('Interaction', () => {


  before(() => {
    this.helperGetRandomIdStub = sandbox.stub(helper, 'getRandomId');
  });


  it('valid mock interaction', () => {
    this.helperGetRandomIdStub.returns('random');
fork icon34
star icon358
watch icon14

+ 4 other calls in file

Ai Example

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

function getUser(userId) {
  // some code to get the user object
}

// create a stub function for getUser
const getUserStub = sinon.stub().returns({
  id: 123,
  name: "John Doe",
  email: "john.doe@example.com",
});

// use the stub function in place of getUser
const user = getUserStub(123);
console.log(user); // output: { id: 123, name: 'John Doe', email: 'john.doe@example.com' }

97
98
99
100
101
102
103
104
105
106

await handlers.setup();

// stub out `createTasks` so that we don't actually create tasks
handlers.realCreateTasks = handlers.createTasks;
handlers.createTasks = sinon.stub();
handlers.queueClient = {
  task: taskId => {
    switch (taskId) {
      case CUSTOM_CHECKRUN_TASKID:
fork icon239
star icon317
watch icon18

+ 29 other calls in file

613
614
615
616
617
618
619
620
621
622
});

it('should accept view, data, and callback arguments', function () {
  var view = 'view';
  var data = { key: 'value' };
  var callback = sinon.stub();

  response.render(view, data, callback);

  expect(response._getRenderView()).to.equal(view);
fork icon130
star icon697
watch icon18

+ 9 other calls in file

21
22
23
24
25
26
27
28
29
30
    return {address: identifier};
  }
};
before('load service and stub dependencies', function () {
  thingRepository = {};
  thingRepository.getThingsById = sinon.stub();
  thingRepository.addThingToUser = sinon.stub();
  thingRepository.deleteThing = sinon.stub();
  thingRepository.updateThing = sinon.stub();
  thingService = proxyquire('../../app/services/thingService',
fork icon30
star icon243
watch icon14

+ 7 other calls in file

104
105
106
107
108
109
110
111
112
113
114
115
test.after.always(async () => {
  await recursivelyDeleteS3Bucket(process.env.system_bucket);
});


test.beforeEach((t) => {
  t.context.queueMessageStub = sinon.stub(rulesHelpers, 'queueMessageForRule');
  t.context.fetchRulesStub = sinon.stub(rulesHelpers, 'fetchRules').returns([]);
});


test.afterEach.always((t) => {
fork icon104
star icon226
watch icon0

190
191
192
193
194
195
196
197
198
199

describe('getMyFluxIPandPort tests', () => {
  let daemonStub;

  beforeEach(() => {
    daemonStub = sinon.stub(daemonServiceBenchmarkRpcs, 'getBenchmarks');
  });

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

+ 51 other calls in file

148
149
150
151
152
153
154
155
156
});

it('should call restartProcessor if processedTrack is still muted after mediaStreamTrack is unmuted', () => {
  videoTrack.addProcessor(processor);
  videoTrack.processedTrack = { muted: true };
  videoTrack._restartProcessor = sinon.stub();
  videoTrack.mediaStreamTrack.emit('unmute');
  sinon.assert.calledOnce(videoTrack._restartProcessor);
});
fork icon208
star icon537
watch icon83

+ 83 other calls in file

14
15
16
17
18
19
20
21
22
23
24
const { CurrencyHelper } = require('../../../../lib/payments/currencies');
const WError = require('verror').WError;
const uuidv4 = require('uuid').v4;
const proxyquire = require('proxyquire').noPreserveCache();
const dbStub = {
  getAccountCustomerByUid: sinon.stub(),
};


const {
  sanitizePlans,
fork icon206
star icon482
watch icon43

+ 4 other calls in file

18
19
20
21
22
23
24
25
26
27
28


const chance = new Chance();
let mockRedis;
const proxyquire = require('proxyquire').noPreserveCache();
const dbStub = {
  getUidAndEmailByStripeCustomerId: sinon.stub(),
};
const {
  MozillaSubscriptionTypes,
  PAYPAL_PAYMENT_ERROR_FUNDING_SOURCE,
fork icon206
star icon482
watch icon43

+ 6 other calls in file

32
33
34
35
36
37
38
39
40
41
// Pull the premock value
const origSchemaFile = constants.reqSchemaFile;
beforeEach(() => {
    // set the mock value
    constants.reqSchemaFile = `${__dirname}/../../../../src/schema/latest/as3-request-schema.json`;
    sinon.stub(util, 'getMgmtPort').resolves(443);
    sinon.stub(util, 'getDeviceInfo').resolves({});
    sinon.stub(tmshUtil, 'getPrimaryAdminUser').resolves('admin');
    sinon.stub(config, 'getAllSettings').resolves({});
});
fork icon57
star icon140
watch icon51

+ 3 other calls in file

71
72
73
74
75
76
77
78
79
80
afterEach(() => {
    sinon.restore();
});

it('should return empty config if error is 404', () => {
    sinon.stub(util, 'iControlRequest').rejects(
        new Error(`body=${JSON.stringify({
            error: {
                code: 404,
                message: '',
fork icon57
star icon140
watch icon51

+ 23 other calls in file

40
41
42
43
44
45
46
47
48
49
});

describe('create', () => {
  let dispatchStub;
  beforeAll(() => {
    dispatchStub = sinon.stub(UtilService, 'dispatchMessageNotification');
  });

  afterEach(() => {
    dispatchStub.reset();
fork icon29
star icon346
watch icon9

+ 2 other calls in file

99
100
101
102
103
104
105
106
107
108
describe('sendmail', () => {
  let sesStub, sesSendEmailStub;

  beforeAll(() => {
    // sinon.stub(aws, 'S3')
    sesSendEmailStub = sinon.stub().returns({
      promise: () => Promise.resolve({
        messageId: randomString(20)
      })
    });
fork icon29
star icon346
watch icon9

+ 13 other calls in file

27
28
29
30
31
32
33
34
35
36
37
38
const path_to_current_file = tools.path.join(__dirname + '/' + filename);
const objects = require('../../docs/ot_misc.json');


const createStubs = () => {
	return {
		writeFileSync: sinon.stub(tools.fs, 'writeFileSync')
	};
};


describe('ot_misc.js', () => {
fork icon45
star icon73
watch icon14

+ 7 other calls in file

35
36
37
38
39
40
41
42
43
44
}

let stub;

before(async function() {
  stub = sinon.stub(logger, 'warn').callsFake((message) => {
    throw new Error(message);
  });
  const posts = await Post.bulkCreate([
    { title: 'Archbishop Lazarus' },
fork icon26
star icon214
watch icon16

+ 4 other calls in file

512
513
514
515
516
517
518
519
520
521

describe('#compare', async () => {
    let processExitStub;

    beforeEach(() => {
        processExitStub = sinon.stub(process, 'exit');
    });

    it('should compare two cto models that require a major change', async () => {
        const aPath = path.resolve(__dirname, 'models', 'compare-a.cto');
fork icon61
star icon75
watch icon18

+ 4 other calls in file

176
177
178
179
180
181
182
183
184
185
186
  assert.end();
});


test('[index] reuse client', function(assert) {
  const costLogger1 = sinon.stub();
  const costLogger2 = sinon.stub();
  const options = {
    table: 'my-table',
    region: 'us-east-1',
    endpoint: 'http://localhost:4567',
fork icon31
star icon77
watch icon98

+ 17 other calls in file