简体   繁体   English

如何在 post 路由上模拟 Express/Node.js 中间件?

[英]How to mock an Express/Node.js middleware on a post route?

I´m writing some tests with chai and mocha and i am having some troubles.我正在用 chai 和 mocha 编写一些测试,但遇到了一些麻烦。 For example, in the route that i paste down here, the LOGOUT calls the isLoggedIn middleware that checks if a user exists in the session.例如,在我粘贴到此处的路由中,LOGOUT 调用 isLoggedIn 中间件来检查会话中是否存在用户。 For example, if a do this:例如,如果这样做:

  it('Logout', function(done) {
    chai.request(baseURL)
    .post('/logout')
    .end(function(err, res) {
      expect(err).to.be.null;
      expect(res).to.have.status(204);
      done();
    });
  });

the test faills cause i get a 401 status code.测试失败导致我收到 401 状态代码。 I am new on this test stuffs.我是这个测试的新手。 I understand that i have to use sinon to get mi test pass, but i can´t get the solution.我知道我必须使用 sinon 来获得 mi 测试通过,但我无法获得解决方案。

This is my route:这是我的路线:

 'use strict'; const express = require('express'); const createError = require('http-errors'); const router = express.Router(); const bcrypt = require('bcrypt'); const User = require('../models/User'); const {isLoggedIn} = require('../helpers/middlewares'); router.post('/logout', isLoggedIn(), (req, res, next) => { req.session.destroy(); return res.status(204).send(); });

This is the Middleware:这是中间件:

'use strict';

const createError = require('http-errors');

exports.isLoggedIn = () => (req, res, next) => {
  if (req.session.user) {
    next();
  } else {
    next(createError(401));
  };
};

Thank you very much!!!非常感谢!!!

In your flow problem in that express middleware initialized during run express application and after becomes unavailable for stubbing.在您的流程问题中,在运行 express 应用程序期间初始化的 express 中间件和之后变得不可用于存根。 My solution is that would init stub before run express application.我的解决方案是在运行快速应用程序之前初始化存根。

test.spec.js: test.spec.js:

const chai = require("chai"),
    sinon = require("sinon"),
    chaiHttp = require("chai-http"),
    initServer = require("./initTestServer"),
    isLoggedInMiddleware = require("./middleware");

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

describe("Resource: /", function() {
    before(function() {
        sinon.stub(isLoggedInMiddleware, "isLoggedIn").callsFake(function() {
            return (req, res, next) => {
                next();
            };
        });

        this.httpServer = initServer();
    });

    after(function() {
        this.httpServer.close();
    });

    describe("#POST /login", function() {
        beforeEach(function() {
            this.sandbox = sinon.createSandbox();
        });

        afterEach(function() {
            this.sandbox.restore();
        });

        it("- should login in system and return data", async function() {
            return chai
                .request(this.httpServer.server)
                .post("/logout")
                .end((err, res) => {
                    expect(err).to.be.null;
                    expect(res).to.have.status(204);
                });
        });
    });
});

initTestServer.js: initTestServer.js:

const isLoggedInMiddleware = require("./middleware");

const initServer = () => {
    const express = require("express");
    const app = express();

    app.post("/logout", isLoggedInMiddleware.isLoggedIn(), (req, res, next) => {
        return res.status(204).send();
    });

    const server = require("http").createServer(app);
    server.listen(3004);

    const close = () => {
        server.close();
        global.console.log(`Close test server connection on ${process.env.PORT}`);
    };

    return { server, close };
};

module.exports = initServer;

Thank you @EduardS for then answer!!谢谢@EduardS 然后回答!! I solved it in a similar way:我以类似的方式解决了它:

  it('Logout', async function(done) {
    sinon.stub(helpers, 'isLoggedIn')
    helpers.isLoggedIn.callsFake((req, res, next) => {
      return (req, res, next) => {
        next();
      };
    })
    app = require('../index')
    chai.request(app)
    .post('/api/auth/logout')
    .end(function(err, res2) {
      expect(res2).to.have.status(204);
      helpers.isLoggedIn.restore()
    })
    done();
  });

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

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