Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在post路由上模拟Express/Node.js中间件?_Node.js_Unit Testing_Mocha.js_Chai_Sinon - Fatal编程技术网

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

如何在post路由上模拟Express/Node.js中间件?,node.js,unit-testing,mocha.js,chai,sinon,Node.js,Unit Testing,Mocha.js,Chai,Sinon,我正在和chai和mocha一起写一些测试,我遇到了一些麻烦。 例如,在我粘贴到这里的路由中,注销调用isLoggedIn中间件,该中间件检查会话中是否存在用户。 例如,如果某个用户执行此操作: it('Logout', function(done) { chai.request(baseURL) .post('/logout') .end(function(err, res) { expect(err).to.be.null; expect(

我正在和chai和mocha一起写一些测试,我遇到了一些麻烦。 例如,在我粘贴到这里的路由中,注销调用isLoggedIn中间件,该中间件检查会话中是否存在用户。 例如,如果某个用户执行此操作:

  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();
    });
  });
测试失败是因为我得到了401状态码。我对这个测试是新手。我知道我必须使用sinon才能通过mi测试,但我无法获得解决方案

这是我的路线:

“严格使用”;
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/middleware');
router.post('/logout',isLoggedIn(),(req,res,next)=>{
req.session.destroy();
返回res.status(204.send();

});在运行express应用程序期间和之后初始化的express中间件中的流问题变得不可用于存根。我的解决方案是在运行express应用程序之前初始化存根

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:

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;

谢谢@EduardS的回答!! 我用类似的方法解决了这个问题:

  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();
  });