当前位置: 首页 > 面试题库 >

Express中间件测试Mocha Chai

颜奇希
2023-03-14
问题内容

有没有一种方法可以快速测试这些中间件:

module.exports = function logMatchingUrls(pattern) {
    return function (req, res, next) {
        if (pattern.test(req.url)) {
            console.log('request url', req.url);
            req.didSomething = true;
        }
        next();
    }
}

我发现的唯一中间件测试是:

module.exports = function(request, response, next) {
    /*
     * Do something to REQUEST or RESPONSE
    **/

    if (!request.didSomething) {
        console.log("dsdsd");
        request.didSomething = true;
        next();
    } else {
        // Something went wrong, throw and error
        var error = new Error();
        error.message = 'Error doing what this does'
        next(error);        
    }
};


describe('Middleware test', function(){

    context('Valid arguments are passed', function() {
        beforeEach(function(done) {
            /* 
             * before each test, reset the REQUEST and RESPONSE variables 
             * to be send into the middle ware
            **/
            requests = httpMocks.createRequest({
                method: 'GET',
                url: '/css/main.css',
                query: {
                    myid: '312'
                }
            });
            responses = httpMocks.createResponse();

            done(); // call done so that the next test can run
        });

        it('does something', function(done) {
            /*
             * Middleware expects to be passed 3 arguments: request, response, and next.
             * We are going to be manually passing REQUEST and RESPONSE into the middleware
             * and create an function callback for next in which we run our tests
            **/
            middleware(responses, responses, function next(error) {
                /*
                 * Usually, we do not pass anything into next except for errors, so because
                 * in this test we are passing valid data in REQUEST we should not get an 
                 * error to be passed in.
                **/
                if (error) { throw new Error('Expected not to receive an error'); }

                // Other Tests Against request and response
                if (!responses.didSomething) { throw new Error('Expected something to be done'); }

                done(); // call done so we can run the next test
            }); // close middleware
        }); // close it
    }); // close context
}); // close describe

这与上面提供的简单中间件(类似于使用回调测试基本功能)很好地配合使用,但是对于更复杂的中间件,我无法使其正常工作。可以测试这种中间件吗?


问题答案:

这里有一个简单的设置,你可以使用,使用chaisinon

var expect = require('chai').expect;
var sinon  = require('sinon');

var middleware = function logMatchingUrls(pattern) {
    return function (req, res, next) {
        if (pattern.test(req.url)) {
            console.log('request url', req.url);
            req.didSomething = true;
        }
        next();
    }
}

describe('my middleware', function() {

  describe('request handler creation', function() {
    var mw;

    beforeEach(function() {
      mw = middleware(/./);
    });

    it('should return a function()', function() {
      expect(mw).to.be.a.Function;
    });

    it('should accept three arguments', function() {
      expect(mw.length).to.equal(3);
    });
  });

  describe('request handler calling', function() {
    it('should call next() once', function() {
      var mw      = middleware(/./);
      var nextSpy = sinon.spy();

      mw({}, {}, nextSpy);
      expect(nextSpy.calledOnce).to.be.true;
    });
  });

  describe('pattern testing', function() {
    ...
  });

});

从那里,您可以为模式匹配等添加更多详细的测试。由于仅使用req.url,因此不必模拟整个Request对象(由Express创建),而只需使用带有url属性的简单对象。



 类似资料:
  • Express middleware The Express middleware modules listed here are maintained by the Expressjs team. Middleware module Description Replaces built-in function (Express 3) body-parser Parse HTTP request

  • 本文向大家介绍express的中间件basicAuth详解,包括了express的中间件basicAuth详解的使用技巧和注意事项,需要的朋友参考一下 basicAuth中间件为网站添加身份认证功能.在使用了该中间件后, 用户访问网站时必须输入用户名与密码,在用户输入了用户名与密码并通过验证之后才能访问网站. 当用户输入的用户名和密码符合条件,中间件会返回true,允许用户访问网站.否则会返回fa

  • 本文向大家介绍express的中间件bodyParser详解,包括了express的中间件bodyParser详解的使用技巧和注意事项,需要的朋友参考一下 bodyParser用于解析客户端请求的body中的内容,内部使用JSON编码处理,url编码处理以及对于文件的上传处理. 下面是一个文件上传的例子. 建立一个1.html页面 上面的XMLHttpRequest对象与FormData对象时HT

  • 本文向大家介绍express的中间件cookieParser详解,包括了express的中间件cookieParser详解的使用技巧和注意事项,需要的朋友参考一下 cookieParser中间件用于获取web浏览器发送的cookie中的内容.在使用了cookieParser中间件后, 代表客户端请求的htto.IncomingMessage对象就具有了一个cookies属性,该属性之为一个对象的数

  • 本文向大家介绍express文件上传中间件Multer详解,包括了express文件上传中间件Multer详解的使用技巧和注意事项,需要的朋友参考一下 前言 Express默认并不处理HTTP请求体中的数据,对于普通请求体(JSON、二进制、字符串)数据,可以使用body-parser中间件。而文件上传(multipart/form-data请求),可以基于请求流处理,也可以使用formidabl

  • 本文向大家介绍深入理解nodejs中Express的中间件,包括了深入理解nodejs中Express的中间件的使用技巧和注意事项,需要的朋友参考一下 Express是一个基于Node.js平台的web应用开发框架,在Node.js基础之上扩展了web应用开发所需要的基础功能,从而使得我们开发Web应用更加方便、更加快捷。 举一个例子: 用node.js实现一个控制台打印“hello server