Skip to content

Instantly share code, notes, and snippets.

@brunops
Created April 7, 2016 22:00
Show Gist options
  • Save brunops/d510bb9410eae2411e10e766ff7a7bce to your computer and use it in GitHub Desktop.
Save brunops/d510bb9410eae2411e10e766ff7a7bce to your computer and use it in GitHub Desktop.
Examples of testing promise controller steps with and without bind
const steps = {
stepBind(req, foo) {
// bla
},
stepNoBind: (req) => (foo) => {
// bla
}
}
// controller
app.get('/foo', (req, res) => {
q({})
.then(steps.stepBind.bind(null, req))
.then(steps.stepNoBind(req))
.catch(errorHandler)
})
// tests
import sinon from 'sinon'
import Steps from './controller-steps'
import Controller from './controller'
describe('controller', () => {
let req,
sandbox
beforeEach(() => {
req = {}
sandbox = sinon.sandbox.create()
sandbox.stub(Steps, 'stepNoBind')
// can't just stub `stepBind`, because the called function is the the *return* of `.bind`
// need to stub `.bind` instead
sandbox.stub(Steps.stepBind, 'bind')
Controller.get(req)
})
afterEach(() => {
sandbox.restore()
})
describe('#get', () => {
it('passes `req` to `stepBind`', () => {
sinon.assert.calledWith(Steps.stepBind.bind, null, req)
})
it('passes `req` to `stepNoBind`', () => {
sinon.assert.calledWith(Steps.stepNoBind, req)
})
})
})
@tdantas
Copy link

tdantas commented Apr 8, 2016




function step(req, cb) {
  //...
}

function wrapper(req) {
  return (cb) => { step(req, cb); }
}

// controller
app.get('/foo', (req, res) => {
    async([
      step.bind(null, req),
      wrapper(req)
    ], finalize);

  function finalize() { 
    //... 
  }
})

Agora são equivalentes o wrapper e bind.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment