简体   繁体   English

锡诺在测试时不会对我的实习生功能进行任何处理。 (ExpressJS)

[英]Sinon doesn't stub my intern fuctions while testing. (ExpressJS)

currently I want to implement sinon stub's for my express routes. 目前,我想为我的快车路线实施sinon stub。 The problem is, that I don't understand why it isnt replacing my functions. 问题是,我不明白为什么它不能代替我的功能。

My test should make a request to my login-route and instead of calling the authenticate function, my login-route should call the fake function. 我的测试应该向我的登录路由发出请求,而不是调用authenticate函数,我的登录路由应该调用假函数。 Any Idea how to do it? 任何想法怎么做?

My project-structure 我的项目结构

/src/http/routes/login.js
/src/http/middlewares/user-midd.js
/test/test.js

test.js: test.js:

const sinon = require('sinon');
const proxyquire = require('proxyquire');

const chai = require('chai');
const expect = chai.expect;
const chaiHttp = require('chai-http');
chai.use(chaiHttp);

const rawapp = require('../src/http/app');

let stub;

try {
    stub = sinon.stub(require('../src/http/middlewares/user-midd').create(),'authenticate')

    proxyquire('../src/http/middlewares/user-midd', {
        'authenticate': stub
    });

    stub.callsFake((request, response, next) => {
        console.log("IM IN FAKE CALL FUNCTION", request, response, next)
        return next()
    })

    chai.request(rawapp())
        .get('/api/v1/de/login')
        .set('X-Xamarin-Client-Version', 1)
        .then((res) => {
            expect(res).to.have.status(200)
            done();
        }).catch(err => console.error(err))
} catch (err) { console.error(err) }

login.js: login.js:

function loginRoute() {
  const authenticate = userMiddleware.create().authenticate;
  const login = new express.Router({ mergeParams: true });

  login.get('/', authenticate, (req, res) => {
    logger.info(new Date(), 'In login route GET /');
    console.log("LOGIN FUNCTION")
    res.status(res.locals.statusCode).json(res.locals.user);
  });

  return login;
}

module.exports.create = loginRoute;

and the lastly my route-middleware: (user-midd.js) 最后是我的路由中间件: (user-midd.js)

    module.exports.create = function create() {
  function authenticate(req, res, next) {
    console.log("AUTHENTIFICATION FUNCTION")
    const authHeader = req.get('authorization');
    const userAuthHeader = req.get('user-authorization') || '';

    if (authHeader) {
      const mandator = req.params.mandator;
      const path = `api/v1/${mandator}/login`;

      logger.info(hostname + path);
      return request
      .get(hostname + path)
      .set('Authorization', authHeader)
      .set('User-Authorization', userAuthHeader)
      .then((mbaasRes) => {
        logger.info('Got response from service - status : ', mbaasRes.statusCode);

        res.locals.user = {};
        res.locals.statusCode = mbaasRes.statusCode;

        if (mbaasRes.body) {
          res.locals.user = mbaasRes.body;
        }

        setUserAuthHeader.setHeader(mbaasRes, res);

        return next();
      })
      .catch((err) => {
        logger.error('service user call failed - err : ', err);
        return next(err);
      });
    }

    const error = {
      msg: 'Unauthorized',
      statusCode: 401,
    };

    return next(error);
  }

  return {
    authenticate,
  };
};

The result of executing my test is: expected { Object (_events, _eventsCount, ...) } to have status code 200 but got 500' 执行测试的结果是: 预期{对象(_events,_eventsCount,...)}的状态码为200,但得到500'

Means that while testing, it doesn't replace the "authenticate" function. 意味着在测试时,它不会替代“验证”功能。 What Im doing wrong? 我在做什么错?

That is not how Sinon works. 诗乃不是这样运作的。 If you want to mock functions required in from other files, you should take a look at proxyquire . 如果要模拟其他文件中所需的功能,则应查看proxyquire

See one of my earlier answers for an explanation. 请参阅我较早的答案之一以获得解释。

proxyquire may not required here, we can just use Sinon . 这里可能不需要proxyquire ,我们可以使用Sinon

This may works 这可能有效

...

describe('app test', function() {
  beforeEach(function() {
    sinon.stub(userMiddleware, 'create').returns({ // use returns of Sinon
      authenticate: sinon.stub.callsFake((request, response, next) => {
        console.log("IM IN FAKE CALL FUNCTION", request, response, next); 
        next();
      })
    });
  });

  afterEach(function() {
    sinon.restore()
  });

  it('success', function(done) {
    chai.request(rawapp())
      .get('/api/v1/de/login')
      .set('X-Xamarin-Client-Version', 1)
      .then((res) => {
          expect(res).to.have.status(200)
          done();
      }).catch(err => console.error(err))
  });
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM