剔除中间件

Stubbing Out Middleware

我正在尝试使用 Sinon 在快速路由中存根一些自定义中间件,但它没有像我预期的那样工作。我希望它不会记录 "I am authenticating..." 而是记录 "Stubbed" 到控制台。看起来 sinon 没有正确地去除中间件。

test/test.js

const chai = require('chai');
const chaiHttp = require('chai-http');
const sinon = require('sinon');
chai.use(chaiHttp);
const should = chai.should();
const auth = require('../auth');

const app = require('../app')

describe('My routes', function() {
    let checkTokenStub;
    beforeEach(()=>{
        checkTokenStub = sinon.stub(auth,'checkToken').callsFake(()=>{
            console.log('Stubbed');
        });;
    })
     it('returns hello', function(done) {
            chai.request(app)
                .get('/')
                .set('X-Auth-Token', 'xyz123')
                .end((err,res)=>{
                    res.text.should.be.eql('Hello')

                    done(err)
                })
        });
    });

app.js

var express = require('express'),
    app = express();
var router = express.Router();
app.use('/', require('./router'));

module.exports = app;

auth.js

exports.checkToken = function(req, res, next) {

    console.log('I am authenticating...')

    var authToken = req.get('x-auth-token');

    if (!authToken)
        return res.sendStatus(401);

    next();
}

router.js

var express = require('express'),
router = express.Router();
auth = require('./auth');

router.get('/', auth.checkToken, function(req, res, next) {
    return res.send('Hello');
});

module.exports = router;

package.json

{
  "name": "sinontest",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "mocha --watch"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "chai": "^4.1.2",
    "chai-http": "^3.0.0",
    "mocha": "^4.0.1",
    "sinon": "^4.1.1"
  },
  "dependencies": {
    "express": "^4.16.4"
  }
}

@Gonzalo.- 在评论中回答了这个问题。我不得不将应用程序的要求移到存根之后。

test.js

const chai = require('chai');
const chaiHttp = require('chai-http');
const sinon = require('sinon');
chai.use(chaiHttp);
const should = chai.should();
const auth = require('../auth');
let app;


describe('My routes', function() {
    let checkTokenStub;
    before(()=>{
        checkTokenStub = sinon.stub(auth,'checkToken').callsFake((req,res,next)=>{
            console.log('Stubbed');
            next()
        });

        app = require('../app')

    })
     it('returns hello', function(done) {
            chai.request(app)
                .get('/')
                .set('X-Auth-Token', 'xyz123')
                .end((err,res)=>{
                    res.text.should.be.eql('Hello')

                    done(err)
                })
        });
    });