describe('TestModule', function() {
beforeEach('setup sandbox', function() {
this.sandbox = sinon.sandbox.create();
this.sandbox.stub(request, 'get');
});
...
afterEach('restore sandbox' function() {
this.sandbox.restore();
});
})
//Other example
const ApiClient = require('./ApiClient');
const request = require('request');
const sinon = require('sinon');
const chai = require('chai');
const sinonChai = require('sinon-chai');
// Allows us to use expect syntax with sinon
chai.use(sinonChai);
const expect = chai.expect;
describe('ApiClient#get', function() {
beforeEach('create ApiClient instance', function() {
this.sandbox = sinon.sandbox.create();
this.sandbox.stub(request, 'get')
this.apiClient = new ApiClient(request, 'api-key');
});
afterEach('restore stub', function() {
this.sandbox.restore();
}
it('yields the request error if the request fails', function(done) {
let requestError = {some: 'error'}
// Respond with a node-style callback error
request.get.yields(requestError);
this.apiClient.get('/posts', (err, response) => {
// Ensure the function was called with expected parameters
expect(request.get).to.have.been.calledWith('/posts', {apiKey: 'api-key'});
// Check that the error is the same object that was yielded.
expect(err).to.equal(requestError);
return done();
});
it('yields INTERNAL_SERVER_ERROR when the response status is 500', function(done) {
// Respond with a 500 to simulate a server error
request.get.yields(null, {status: 500});
this.apiClient.get('/posts', (err, response) => {
// Ensure the function was called with expected parameters
expect(request.get).to.have.been.calledWith('/posts', {apiKey: 'api-key'});
// Check that the error is the right string.
expect(err).to.equal('INTERNAL_SERVER_ERROR');
return done();
});
it('yields an AUTH_ERROR when the response status is 403', function(done) {
request.get.yields(null, {status: 403}); // Respond with a 403
this.apiClient.get('/posts', (err, response) => {
// Ensure the function was called with expected parameters
expect(request.get).to.have.been.calledWith('/posts', {apiKey: 'api-key'});
// Check that the error is the right string.
expect(err).to.have.property('message', 'AUTH_ERROR')
// Test for publicly visible side effects
expect(this.apiClient.isApiKeyValid).to.equal(false);
return done();
});
});