title: Mocking modules in Node.js for unit testing
body: <p>I want to unit test some functions in a node.js module. I think that mocking a 3rd module would be helpful. In particular to avoid hitting the database</p>
  
  <pre><code># models/account.coffee
  register = (email, password)-&gt;
     sha_sum.update(password)
     pw = sha_sum.digest('hex')
     user = 
        email: email
        password: sha_sum.digest('hex')
  
     users_db.save user, (err, doc)-&gt;
        register_callback(err)
  
  account_module = 
     register: register
  
  module.exports = account_module
  </code></pre>
  
  <p>This is the module that i want to test</p>
  
  <pre><code># routes/auth.coffee
  account = require '../models/account'
  
  exports.auth = 
     post_signup: (req, res)-&gt;
        email = req.body.email
        password = req.body.password
        if email and password
            account.register(email, password)
            res.send 200
        else
            res.send 400
  </code></pre>
  
  <p>I want to be able to test that hitting this url with the correct body in the post calls the <code>account.register</code> function but i don't want the test to hit the database. I may not have implemented the account module yet. </p>
  
  <p>The jasmine spec
      # specs/auth.test.coffee
      describe 'signup', -></p>
  
  <pre><code>   request = require 'request' 
     it 'should signup a user with username and password', (done)-&gt;
  
         spyOn(account, 'register') # this does not work, account.register still called
         url = root + '/signup'
         headers =
             "Content-Type": "application/json" 
         data = 
             email: 'user@email.com'
             password: 'pw'
         body = JSON.stringify(data)
         request {url: url, method: 'POST',json: data, headers: headers }, (err, response, body)-&gt;
  
             expect(response.statusCode).toEqual(200)
             done()
  </code></pre>
  
  <p>I have looked into several mocking libraries for node.js (<a href="https://github.com/easternbloc/Syringe" rel="noreferrer">https://github.com/easternbloc/Syringe</a>, <a href="https://github.com/felixge/node-sandboxed-module" rel="noreferrer">https://github.com/felixge/node-sandboxed-module</a>) but so far no success. Whatever i try in the spec, the <code>account.register</code> always get executed. Is this whole approach flawed?</p>