相关疑难解决方法(0)

如何在Express中模拟中间件以跳过单元测试的身份验证?

我在Express中有以下内容

 //index.js

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

 router.post('/sync', auth.isAuthenticated, service.synchronise);

 module.exports = router;
Run Code Online (Sandbox Code Playgroud)

我想覆盖或模拟isAuthenticated返回此

auth.isAuthenticated = function(req, res, next) { 
  return next(); 
}
Run Code Online (Sandbox Code Playgroud)

这是我的单元测试:

it('it should return a 200 response', function(done) {

  //proxyquire here?

  request(app).post('/subscriptions/sync')
  .set('Authorization','Bearer '+ authToken)
  .send({receipt: newSubscriptionReceipt })
  .expect(200,done);
});
Run Code Online (Sandbox Code Playgroud)

我尝试使用proxyquire模拟index.js - 我想我需要存根路由器?我也试过在测试中覆盖

app.use('/subscriptions', require('./api/subscription'));
Run Code Online (Sandbox Code Playgroud)

必须有一种简单的方法来模拟它,所以我不需要验证请求.有任何想法吗?

mocha.js node.js express sinon proxyquire

27
推荐指数
1
解决办法
8725
查看次数

Sinon存根被跳过作为节点表达中间件

我正在尝试测试特定路线的行为。即使我创建存根,它也会继续运行中间件。我希望事件认证暂时通过。我了解到,这并不是真正的“单元”测试。我快到那里了。我还简化了代码。这是要测试的代码:

const { rejectUnauthenticated } = require('../modules/event-authentication.middleware');

router.get('/event', rejectUnauthenticated, (req, res) => {
  res.sendStatus(200);
});
Run Code Online (Sandbox Code Playgroud)

这是我要跳过的中间件:

const rejectUnauthenticated = async (req, res, next) => {
  const { secretKey } = req.query;
  if (secretKey) {
    next();
  } else {
    res.status(403).send('Forbidden. Must include Secret Key for Event.');
  }
};

module.exports = {
  rejectUnauthenticated,
};
Run Code Online (Sandbox Code Playgroud)

测试文件:

const chai = require('chai');
const chaiHttp = require('chai-http');
const sinon = require('sinon');
let app;
const authenticationMiddleware = require('../server/modules/event-authentication.middleware');

const { expect } = chai;
chai.use(chaiHttp);

describe('with correct …
Run Code Online (Sandbox Code Playgroud)

unit-testing mocha.js node.js sinon chai

6
推荐指数
1
解决办法
913
查看次数

标签 统计

mocha.js ×2

node.js ×2

sinon ×2

chai ×1

express ×1

proxyquire ×1

unit-testing ×1