存根中间件

时间:2019-03-30 17:37:34

标签: node.js sinon chai chai-http

我正在尝试使用Sinon在快速路由中存入一些自定义中间件,但是它没有按我期望的那样工作。我希望它不会记录“我正在验证...”,而是记录“存根”到控制台。看起来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"
  }
}

1 个答案:

答案 0 :(得分:1)

@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)
                })
        });
    });