Sinon存根在测试文件之外被忽略

时间:2019-03-08 04:09:40

标签: node.js express mocha passport.js sinon

我正在使用mocha,chai和sinon测试一些经过身份验证的API路由。我正在使用passport.authenticate()作为中间件来验证路由:

{
    "minVersion": "0.1",
    "headerImage": "",
    "tintColor": "",
    "tabs": [
        {
            "tabname": "Changelog",
            "views": [
                {
                    "title": "1.0 copy",
                    "useBoldText": true,
                    "useBottomMargin": true,
                    "class": "DepictionSubheaderView"
                },
                {
                    "markdown": "\t\n• Initial Release copy",
                    "useSpacing": false,
                    "class": "DepictionMarkdownView"
                },
                {
                    "markdown": "<small style=\"color: #999; margin-top: -8px;\">Released 3/7/2019</small> copy",
                    "useRawFormat": true,
                    "class": "DepictionMarkdownView"
                },
                {
                    "title": "1.0 copy",
                    "useBoldText": true,
                    "useBottomMargin": true,
                    "class": "DepictionSubheaderView"
                },
                {
                    "markdown": "\t\n• Initial Release copy",
                    "useSpacing": false,
                    "class": "DepictionMarkdownView"
                },
                {
                    "markdown": "<small style=\"color: #999; margin-top: -8px;\">Released 3/7/2019</small> copy",
                    "useRawFormat": true,
                    "class": "DepictionMarkdownView"
                }
            ],
            "class": "DepictionStackView"
        }
    ],
    "class": "DepictionTabView"
}

然后,在我的测试套件中,我正在使用sinon对护照进行存根验证。

const router = require('express').Router();
const passport = require('passport');

router.post('/route', 
            passport.authenticate('jwt', {session:false}), 
            function(req,res) {
                return res.status(200);
            });
module.exports = router;

现在,当我运行测试套件时,我看到它打印出以下内容:

const chai = require('chai');
const chaiHttp = require('chai-http');
const sinon = require('sinon');
const passport = require('passport');
const server = require('../../app');
const expect = chai.expect;

chai.use(chaiHttp);
describe('route', function() {
    before(function(done) {
        sinon.stub(passport, 'authenticate').callsFake(function(test, args) {
            console.log('Auth stub');
        });
        console.log('stub registered');
        passport.authenticate('jwt', {session:false});
        done();
    });
    after(function(done) {
        console.log('after hook');
        passport.authenticate.restore();
        done();
    });
    describe('POST /route', function() {
        it('should post', function(done) {
            console.log('starting test');
            chai.request(server)
                .post('/route')
                .end(function(err,res) {
                    expect(res).to.have.status(200);
                    done();
                });
         });
     });
});

由此可见,存根注册后,我可以在测试文件中调用它并正确存根。但是,当在route.post()中调用passport.authenticate()时,它是实际的passport.authenticate(),并且由于我未通过身份验证而发送状态为401的响应。

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

您的代码在运行后立即调用passport.authenticate ,并在需要时立即运行

由于在创建stub之前需要在测试开始时输入代码,所以代码最终将调用真实的passport.authenticate

要使这样的代码调用stub,必须先设置stub ,然后再需要代码

const chai = require('chai');
const chaiHttp = require('chai-http');
const sinon = require('sinon');
const passport = require('passport');
// const server = require('../../app');  <= don't require your code here...
const expect = chai.expect;

chai.use(chaiHttp);
describe('route', function () {
  before(function (done) {
    sinon.stub(passport, 'authenticate').callsFake(function (test, args) {
      console.log('Auth stub');
    });
    console.log('stub registered');
    passport.authenticate('jwt', { session: false });
    done();
  });
  after(function (done) {
    console.log('after hook');
    passport.authenticate.restore();
    done();
  });
  describe('POST /route', function () {
    it('should post', function (done) {
      console.log('starting test');
      const server = require('../../app');  // <= require it AFTER creating the stub
      chai.request(server)
        .post('/route')
        .end(function (err, res) {
          expect(res).to.have.status(200);
          done();
        });
    });
  });
});

答案 1 :(得分:0)

与sinon存根有关的一个小笔记,我设法使用以下语法使其起作用:

# mod_rewrite starts here

RewriteEngine on

# does not apply to existing directories, meaning if the folder exists on the server then don't change anything and don't run the Rule!

RewriteCond %{REQUEST_FILENAME} !-d

# Check for file in directory with .html extension

RewriteCond %{REQUEST_FILENAME}\.html -f

# Here we actually show the page that has the .html extension

RewriteRule ^(.*)$ $1.html [NC,L]s

主要内容是:

  1. 将用户数据添加到req.user
  2. 执行next()使代码流继续进入下一个中间件

回顾一下,这不是实际测试身份验证策略的方法,而是在您要测试路由器结果的情况下绕过它的方法。