Original function is called instead of stub

express, javascript, mocha.js, sinon, stub

Solution

You'll likely need to create your stubs before requiring/creating the `app`.

var request = require('supertest')
  , sinon = require('sinon')
  , retro = require('../routes/retro');

var stubRetroList = sinon.stub(retro, 'list');

var app = require('../app');

// ...

    stubRetroList.callCount.should.equal(1);

This allows `retro.list` to be updated before it's passed to the route:

app.get('/retro', retro.list);

The issue is probably because `retro.list` isn't being passed-by-reference (pointer), but is rather a reference that's passed-by-value (copied). So, though `sinon.stub()` is altering `retro.list`, it wouldn't affect the copy that the `'/retro'` route already had.

Problem

I'm having an issue getting Sinon's stub to work correctly for me. When I stub `list` on `retro` and the test runs, `app.get('/retro', retro.list)` is executing the original function `retro.list` instead of the stub. Since this happens, the test fails because the stub's `callCount` is 0. I'm more familiar with coffeescript and I have stubbed things in the same way. Is there something I'm not understanding about Javascript's scoping, or how the `require('../routes/retro')` works, or is `retro` is not the same in `app.js` and `test.js`. Much thanks for the help and code below. test.js: ``` var request = require('supertest') , retro = require('../routes/retro') , app = require('../app') , sinon = require('sinon'); require('should'); describe('GET /retro', function() { // less involved, but maybe stupid to test it('should call retro.list', function(done) { var stub = sinon.stub(retro, 'list'); request(app) .get('/retro') .end(function(err, res){ stub.callCount.should.equal(1); if (err) return done(err); done(); }) }) }) ``` app.js: ``` var express = require('express') , config = require('./config') , routes = require('./routes') , retro = require('./routes/retro'); var app = express(); config(app); app.get('/', routes.index); app.get('/retro', retro.list); module.exports = app; ``` retro.js: ``` var retro = { list: function(req, res){ console.log('actual called'); res.send("respond with a resource"); } } module.exports = retro; ```

Original source