代码之家  ›  专栏  ›  技术社区  ›  physicsboy

检查中间件是从http调用调用调用的

  •  0
  • physicsboy  · 技术社区  · 7 年前

    如何测试一个定制中间件实际上是从标准HTTP事件调用的?

    即,中间件从以下位置调用:

    我的控制器.js

    router.get('/some/endpoint', [myMiddleware()], (req, res, next) => {
        // Code to do whatever here
    });
    

    中间件本身可以定义为:

    module.exports = () => {
        // Middleware code in here
    }
    

    我的任务是检查是否从我的单元测试中调用了中间件一次,但是我找不到与此相关的文档。

    我的测试.js

    it('Should return whatever from GET call', () => {
        return request(app).get('/some/endpoint')
            .expect(200)
            .expect(res => {res.body.should.deep.equal(bodyValue)});
        // How would I place code in here to check that MyMiddleware is called? 
        // ie. sinon.assert.calledOnce(MyMiddleware)
    });
    

    我不想用中情局,但是我不能。。。我的尝试是:

    const mwSpy = sinon.spy(require('path to middleware file'));
    
    sinon.assert(calledOnce(mwSpy));
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   oligofren    7 年前

    通常的方法是将其分成两个测试,一个集成测试和一个单元测试。

    1. 我在 router.get
    2. 我的中间件做得对吗?

    第一部分基本上是测试expressapi是否执行了文档中所说的内容。这不是单元测试的目的(这是标记的) unit-testing ),但由于您已经在使用HTTP请求来测试端点,我想这并不是您想要的:您基本上是在为您的系统创建验证测试。

    但是,您仍然可以在没有HTTP的情况下测试Express路由,比如 I detail in the answer to this question ,关于如何以编程方式测试路由器(更快的测试,没有http),但不只是坚持你所拥有的。

    所以最基本的问题是:“我的任务是检查是否从我的单元测试中调用了中间件一次”。你似乎并不关心中间件是否做得对,只关心它被调用了,这就要求我们是否应该测试中间件或层 中间件。

    在这两种情况下,您都需要找到一种注入测试间谍的方法。或者编写一个小实用程序方法来注入该间谍: function setMiddleware(module){ middleware = module; } 或者你用一些工具 proxyquire . 看到了吗 this tutorial on Sinon's homepage for background .

    it('Should return whatever from GET call', () => {
      var middlewareFake = sinon.fake();
      // I am assuming it's the actual app object you are referencing below in the request(app) line
      var app = proxyquire('../app/index.js', { './my-middleware': middlewareFake });
    
      //
      return request(app).get('/some/endpoint')
        .expect(200)
        .expect(res => {
          res.body.should.deep.equal(bodyValue)
    
          expect(middlewareFake).was.called;
        });
    });