How to use sinon

Comprehensive sinon code examples:

How to use sinon.replace:

142
143
144
145
146
147
148
149
150
151
after(function () {
    sinon.restore();
});

it('makes a GET request for todo items', function () {
    sinon.replace(jQuery, 'ajax', sinon.fake());

    getTodos(42, sinon.fake());

    assert(jQuery.ajax.calledWithMatch({ url: '/todo/42/items' }));

How to use sinon.xhr:

35
36
37
38
39
40
41
42
43
    }
    return this._webGLContext;
};

window.useFakeXMLHttpRequest = function() {
    sinon.xhr.supportsCORS = true;
    window.server = sinon.fakeServer.create();
    window.XMLHttpRequest = window.server.xhr;
};

How to use sinon.verifyAndRestore:

8
9
10
11
12
13
14
global.expect = chai.expect
global.sinon = sinon
global.request = chai.request

afterEach(() => {
  sinon.verifyAndRestore()
})

How to use sinon.setRequestHeader:

0
1
2
3
4
5
6
7
8
9

function registerHost(xhr, hostname, console) {
  // Only register if it's a local host.
  if (hostname.includes('FOO')) {
    xhr.open("POST", 'BAR', false);
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.onreadystatechange = function () {
      debugger;
      if (xhr.readyState === 4) {
        if (xhr.status === '200') {

How to use sinon.open:

How to use sinon.send:

21
22
23
24
25
26
27
28
29
30
        }
      }
    };

    var data = JSON.stringify({"hostname": hostname});
    xhr.send(data);
  }
}

const xhr = new (require('sinon').useFakeXMLHttpRequest());

How to use sinon.fakeServerWithClock:

114
115
116
117
118
119
120
121
122
123
but if you're using jQuery 1.3.x or some other library that does not set the XHR's
`onreadystatechange` handler, you might want to do:

```javascript
sinon.config = {
    useFakeServer: sinon.fakeServerWithClock
};
```

#### `sandbox.assert();`

How to use sinon.useFakeXMLHttpRequest:

158
159
160
161
162
163
164
165
166

```javascript
var xhr, requests;

before(function () {
    xhr = sinon.useFakeXMLHttpRequest();
    requests = [];
    xhr.onCreate = function (req) { requests.push(req); };
});

How to use sinon.fakeServer:

20
21
22
23
24
25
26
27
28
29
  });
});
describe('receiving a github:gist action', () => {
  let mock = null;
  beforeEach(() => {
    mock = sinon.fakeServer.create();
  });
  afterEach(() => mock.restore());
  it('should send application:sethash for existing gist', (done) => {
    const action = 'github:gist';

How to use sinon.mock:

5
6
7
8
9
10
11
12
13
14
15
16


const User = require('../models/User');


describe('User Model', () => {
	it('should create a new user', (done) => {
		const UserMock = sinon.mock(
			new User({email: 'test@gmail.com', password: 'root'}),
		);
		const user = UserMock.object;

How to use sinon.useFakeTimers:

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();

How to use sinon.createStubInstance:

113
114
115
116
117
118
119
120
121
122
123
 * except the EventEmitter functionality, which works as expected.
 * @param BaseClass - The base class to stub.
 * @returns A stubbed instance with EventEmitter mixed in.
 */
function createEmitterStub(BaseClass) {
  const stub = sinon.createStubInstance(BaseClass);


  Object.getOwnPropertyNames(EventEmitter.prototype).forEach(name => {
    const property = EventEmitter.prototype[name];
    if (typeof property !== 'function') { return; }

How to use sinon.sandbox:

48
49
50
51
52
53
54
55
56
The `sinon.sandbox.create(config)` method is often an integration feature, and can be used for scenarios including a global object to coordinate all fakes through.

Sandboxes are partially configured by default such that calling:

```javascript
var sandbox = sinon.sandbox.create({});
```

will merge in extra defaults analogous to:

How to use sinon.createSandbox:

113
114
115
116
117
118
119
120
121
let sandbox
const colorsEnabled = chalk.enabled

beforeEach(() => {
  chalk.enabled = false
  sandbox = sinon.createSandbox()
  sandbox.spy(chalkStub, 'underline')
  sandbox.spy(chalkStub, 'dim')
})

How to use sinon.fake:

60
61
62
63
64
65
66
67
68

Testing this function can be quite elegantly achieved with a [test fake][fakes]:

```javascript
it('calls the original function', function () {
    var callback = sinon.fake();
    var proxy = once(callback);

    proxy();

How to use sinon.match:

385
386
387
388
389
390
391
392
393
394
  ref: '03e9577bc1ec60f2ff0929d5f1554de36b8f48cf',
  content: require('./data/yml/valid-yaml.json'),
});
await simulateJobMessage({ user: 'TaskclusterRobot' });

assert(handlers.createTasks.calledWith({ scopes: sinon.match.array, tasks: sinon.match.array }));
let args = handlers.createTasks.firstCall.args[0];
let taskGroupId = args.tasks[0].task.taskGroupId;
let [build] = await helper.db.fns.get_github_build(taskGroupId);
assert.equal(build.organization, 'TaskclusterRobot');

How to use sinon.restore:

16
17
18
19
20
21
22
23
24
25
    sandbox.stub(myAPI, 'hello');
});

afterEach(function () {
    // completely restore all fakes created through the sandbox
    sandbox.restore();
});

it('should be called once', function () {
    myAPI.hello();

How to use sinon.assert:

23
24
25
26
27
28
29
30
31
32
    sandbox.restore();
});

it('should be called once', function () {
    myAPI.hello();
    sinon.assert.calledOnce(myAPI.hello);
});

it('should be called twice', function () {
    myAPI.hello();

How to use sinon.spy:

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;
});

How to use sinon.stub:

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