相关疑难解决方法(0)

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
查看次数

在 Express 中测试中间件而不创建重新创建服务器的简单方法?

我希望能够在每次测试的基础上存根我的中间件功能。正如此处阐明的,问题是我不能仅仅存根我的中间件函数,因为节点已经缓存了中间件函数,所以我不能存根它,因为我在一开始创建了我的应用程序。

const request = require("supertest");
const { expect } = require("chai");
const sinon = require('sinon');
const auth = require ("../utils/auth-middleware")
const adminStub = sinon.stub(auth, "isAdmin").callsFake((req, res, next) => next());
const app = require("../app.js"); // As soon as I create this, the middleware isAdmin function becomes cached and no longer mutable
Run Code Online (Sandbox Code Playgroud)

以上作为链接的SO答案中描述的解决方案,但我不喜欢那样为了恢复存根或修改假,我必须完全重新创建服务器。

我想知道是否有更好、更优雅的方法来解决 Node 首先缓存这些函数的事实require。我正在研究可能使用proxyquireordecache但两者似乎都提供了解决方法而不是可持续的解决方案(尽管我很可能在这里错了)。

javascript mocha.js node.js sinon

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

标签 统计

mocha.js ×2

node.js ×2

sinon ×2

chai ×1

javascript ×1

unit-testing ×1