Skip to content

Instantly share code, notes, and snippets.

@nackjicholson
Created April 26, 2015 02:27
Show Gist options
  • Save nackjicholson/837bb53327a627dacf53 to your computer and use it in GitHub Desktop.
Save nackjicholson/837bb53327a627dacf53 to your computer and use it in GitHub Desktop.
Better tests, proxyquire vs injection vs mockless
var assert = require('assert')
var sinon = require('sinon')
var dependency = require('dependency')
var sut = require('./injection-sut')
describe('sut', function () {
var methodStub
beforeEach(function () {
methodStub = sinon.stub(dependency, 'method')
})
afterEach(function () {
dependency.method.restore()
})
it('should return value from call to dependency.method', function () {
methodStub.returns('dependency.method.response')
assert.equal(sut(dependency), 'dependency.method.response')
assert(methodStub.calledOnce)
assert.equal(methodStub.args[0][0], 'bagel')
})
})
module.exports = function sut (dependency) {
return dependency.method('bagel')
}
var assert = require('assert')
var sut = require('sut')
describe('sut', function () {
var dependency = {}
it('should return value from call to dependency.method', function () {
dependency.method = function (arg) {
assert.equal(arg, 'bagel')
return 'dependency.method.response'
}
assert.equal(sut(dependency), 'dependency.method.response')
})
})
// Pros:
// * less setup/teardown code
// * straight forward asserts
// * vanilla (no devDependency modules)
// Cons:
// * It's possible to get false negatives. If dependency removes ".method",
the test will still pass even though code doesn't work. (this is a big con)
// * Gets repetitive writing the method in every test.
var proxyquire = require('proxyquire')
var assert = require('assert')
var sinon = require('sinon')
var dependency = require('dependency')
describe('sut', function () {
var methodStub
var sut
beforeEach(function () {
methodStub = sinon.stub(dependency, 'method')
sut = proxyquire('./require-sut', {
dependency: dependency
})
})
afterEach(function () {
dependency.method.restore()
})
it('should return value from call to dependency.method', function () {
methodStub.returns('dependency.method.response')
assert.equal(sut(), 'dependency.method.response')
assert(methodStub.calledOnce)
assert.equal(methodStub.args[0][0], 'bagel')
})
})
// Pros:
// * Can't get a false negative
// Cons:
// * A lot of setup/teardown
var dependency = require('dependency')
module.exports = function sut () {
return dependency.method('bagel')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment