Created
July 10, 2017 09:24
-
-
Save 80xer/a873fd5c62846a1f32981079e626f3a4 to your computer and use it in GitHub Desktop.
sinon practices
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
import sinon from 'sinon'; | |
import chai from 'chai'; | |
const assert = chai.assert; | |
const Database = { | |
save: (user, cb) => { | |
cb(); | |
}, | |
}; | |
function setupNewUser(info, callback) { | |
const user = { | |
name: info.name, | |
nameLowercase: info.name.toLowerCase(), | |
}; | |
try { | |
Database.save(user, callback); | |
} catch (err) { | |
callback(err); | |
} | |
} | |
describe('SINON SPY', () => { | |
let save; | |
beforeEach(() => (save = sinon.spy(Database, 'save'))); | |
afterEach(() => save.restore()); | |
it('should call save once', () => { | |
setupNewUser({ name: 'test' }, () => {}); | |
assert(save.calledOnce); | |
}); | |
it('should pass object with correct values to save', () => { | |
const info = { name: 'test' }; | |
const expectedUser = { | |
name: info.name, | |
nameLowercase: info.name.toLowerCase(), | |
}; | |
setupNewUser(info, () => {}); | |
assert(save.calledWith(expectedUser)); | |
}); | |
}); | |
describe('SINON STUB', () => { | |
let save; | |
beforeEach(() => (save = sinon.stub(Database, 'save'))); | |
afterEach(() => save.restore()); | |
it('should pass object with correct values to save', () => { | |
const info = { name: 'test' }; | |
const expectedUser = { | |
name: info.name, | |
nameLowercase: info.name.toLowerCase(), | |
}; | |
setupNewUser(info, () => {}); | |
assert(save.calledWith(expectedUser)); | |
}); | |
it('should pass the error into the callback if save fails', () => { | |
const expectedError = new Error('oops'); | |
const callback = sinon.spy(); | |
save.throws(expectedError); | |
setupNewUser({ name: 'foo' }, callback); | |
assert(callback.calledWith(expectedError)); | |
}); | |
it('should pass the database result into the callback', () => { | |
const expectedResult = { success: true }; | |
const callback = sinon.spy(); | |
save.yields(null, expectedResult); | |
setupNewUser({ name: 'foo' }, callback); | |
assert(callback.calledWith(null, expectedResult)); | |
}); | |
}); | |
describe('SINON MOCK', () => { | |
it('should pass object with correct values to save only once', () => { | |
const info = { name: 'test' }; | |
const expectedUser = { | |
name: info.name, | |
nameLowercase: info.name.toLowerCase(), | |
}; | |
const database = sinon.mock(Database); | |
database.expects('save').once().withArgs(expectedUser); | |
setupNewUser(info, () => {}); | |
database.verify(); | |
database.restore(); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment