How to use the useFakeTimers function from sinon

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

sinon.useFakeTimers is a function that replaces the native timers in JavaScript with fake timers, allowing for the manipulation of time for testing purposes.

107
108
109
110
111
112
113
114
115
  t.equal(typeof api.run, 'function', 'it has a run method');
  t.end();
});

test('running commands', (t) => {
  var clock = sinon.useFakeTimers();
  var instance = buildWidget({ id: 'foo', command: 'command', css: ''});
  var widget = instance.implementation();
  var server = makeFakeServer();
fork icon10
star icon153
watch icon10

+ 3 other calls in file

9
10
11
12
13
14
15
16
17
18

describe('paypro', function() {
  var xhr, httpNode, clock;
  before(function() {
    // Stub time before cert expiration at Mar 27 2016
    clock = sinon.useFakeTimers(1459105693843);

    xhr = {};
    xhr.onCreate = function(req) {};
    xhr.open = function(method, url) {};
fork icon4
star icon1
watch icon6

+ 3 other calls in file

How does sinon.useFakeTimers work?

sinon.useFakeTimers() is a method provided by Sinon.js that creates a fake timer that can be used to control time-based behavior during tests. This method replaces the global setTimeout(), setInterval(), clearTimeout(), and clearInterval() functions with a Sinon implementation that can be controlled by the test, allowing for more precise and predictable testing of time-based code.

231
232
233
234
235
236
237
238
239
240
Thanks to Sinon.JS' time-bending abilities, testing it is easy:

```javascript
var clock;

before(function () { clock = sinon.useFakeTimers(); });
after(function () { clock.restore(); });

it('calls callback after 100ms', function () {
    var callback = sinon.fake();
fork icon810
star icon0
watch icon2

+ 3 other calls in file

23
24
25
26
27
28
29
30
31
32
let videoTrack;
let mediaStreamTrack;
let processedTrack;

beforeEach(() => {
  clock = sinon.useFakeTimers();

  mediaStreamTrackSettings = {
    width: 1280,
    height: 720,
fork icon208
star icon537
watch icon83

+ 2 other calls in file

Ai Example

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

// Create a clock object
const clock = sinon.useFakeTimers();

// Set up a function to be called after a delay
const delayedFunc = sinon.fake();
setTimeout(delayedFunc, 1000);

// Fast-forward the clock by 1 second
clock.tick(1000);

// Check that the function was called
sinon.assert.calledOnce(delayedFunc);

// Restore the clock
clock.restore();

In this example, sinon.useFakeTimers() is used to create a fake clock object that can be used to manipulate the passage of time in the application. A function is then set to be called after a 1 second delay, and the clock is fast-forwarded by 1 second using clock.tick(1000). The sinon.assert.calledOnce() method is then used to check that the function was called, and the clock is restored using clock.restore().

2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
describe('removeCustomerPaypalAgreement', () => {
  it('removes billing agreement id', async () => {
    const paypalCustomer = deepCopy(customer1);
    sandbox.stub(stripeHelper.stripe.customers, 'update').resolves({});
    const now = new Date();
    const clock = sinon.useFakeTimers(now.getTime());

    sandbox.stub(dbStub, 'updatePayPalBA').returns(0);
    stripeFirestore.insertCustomerRecordWithBackfill = sandbox
      .stub()
fork icon206
star icon482
watch icon43

8
9
10
11
12
13
14
15
16
17
18


describe('Strategy', function() {
  var clock;
  
  beforeEach(function() {
    clock = sinon.useFakeTimers(1311280970000);
  });
  
  afterEach(function() {
    clock.restore();
fork icon0
star icon2
watch icon3

93
94
95
96
97
98
99
100
101
102
if (clockOptions !== undefined) {
    await context.addInitScript({
        path: path.join(__dirname, '../', './node_modules/sinon/pkg/sinon.js')
    });
    await context.addInitScript((options) => {
        window.__clock = sinon.useFakeTimers(options);
    }, clockOptions);
}

await use(context);
fork icon0
star icon0
watch icon274

+ 6 other calls in file

425
426
427
428
429
430
431
432
433
434

    expect(observer.intervalObject).to.not.be.undefined;
});

it('should trigger update when interval is exceeded with method periodic', async () => {
    const clock = sinon.useFakeTimers();

    const senderUuid = 'senderUuid';
    const messenger = {
        getUUID: sinon.stub().returns(senderUuid),
fork icon0
star icon0
watch icon1

+ 9 other calls in file

1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
describe('keepalive', function () {
  let clock

  // eslint-disable-next-line
  beforeEach(function () {
    clock = sinon.useFakeTimers()
  })

  afterEach(function () {
    clock.restore()
fork icon0
star icon0
watch icon1

+ 3 other calls in file

159
160
161
162
163
164
165
166
167

    assert.deepEqual(result, '2022-12-01T01:01:30.000Z');
});

it('can get date for draft post', function () {
    const clock = sinon.useFakeTimers(); // required because assertion could be 1ms off
    const result = JSONToHTML.getPostDate({});
    const expected = new Date().toISOString();
    clock.restore();
fork icon0
star icon0
watch icon0

1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
            etag: anyEtag
        });
});

it('Can subscribe to a newsletter', async function () {
    const clock = sinon.useFakeTimers(Date.now());
    const memberToChange = {
        name: 'change me',
        email: 'member3change@test.com',
        newsletters: [
fork icon0
star icon0
watch icon0

+ 4 other calls in file

52
53
54
55
56
57
58
59
60
61
  await this.User.sync({ force: true });
});

describe('Fake Timers Suite', () => {
  before(function () {
    this.clock = sinon.useFakeTimers();
  });

  after(function () {
    this.clock.restore();
fork icon0
star icon0
watch icon420

102
103
104
105
106
107
108
109
110
111
let date;
let string;
let now;

beforeEach(function () {
  clock = sinon.useFakeTimers(unix);
  now = moment();
  mmnt = moment(anchor);
  date = mmnt.toDate();
  string = mmnt.format(format);
fork icon0
star icon0
watch icon2

+ 39 other calls in file

182
183
184
185
186
187
188
189
190
191
            ]
        });
});

it('Can change existing feedback', async function () {
    clock = sinon.useFakeTimers(new Date());
    const postId = fixtureManager.get('posts', 1).id;

    const {body} = await membersAgent
        .post(`/api/feedback/?uuid=${memberUuid}`)
fork icon0
star icon0
watch icon2

+ 2 other calls in file

157
158
159
160
161
162
163
164
165
166

beforeEach(async function () {
    loggingStub = sinon.stub(logging, 'info');
    const threeMonthsAgo = new Date();
    threeMonthsAgo.setMonth(threeMonthsAgo.getMonth() - 3);
    clock = sinon.useFakeTimers({
        now: threeMonthsAgo.getTime(),
        toFake: ['setTimeout']
    });
    sinon.createSandbox();
fork icon0
star icon0
watch icon2

+ 2 other calls in file