如何测试简单的中间件

时间:2018-12-01 16:14:29

标签: javascript node.js unit-testing jestjs

我有3种这样的中间件:

module.exports = {

    validateRequest: function(req, res, next) {
        return new Promise((resolve, reject) => {
            if(!req.body.title || !req.body.location || !req.body.description || !req.body.author){
            Promise.reject('Invalid')
            res.status(errCode.invalid_input).json({
              message: 'Invalid input'
            })
         }
     })
    },
    sendEmail: ...,
    saveToDatabase: ...

}

我在路线中这样使用它们:

const { validateRequest, sendEmail, saveToDatabase } = require('./create')
...
api.post('/create', validateRequest, sendEmail, saveToDatabase);

它有效,但是我无法测试。这是我的尝试(失败):

test('create.validateRequest should throw error if incorrect user inputs', (done) => {
  const next = jest.fn();
  const req = httpMocks.createRequest({ 
    body: { 
            title: 'A new world!',
            location: '...bunch of talks...',
            description: '...'  
    }
  });
  const res = httpMocks.createResponse();
  expect(validateRequest(req, res, next)).rejects.toEqual('Invalid')

})

Jest输出以下内容:
错误
   无效

  

问题:如何测试此validateRequest中间件?

1 个答案:

答案 0 :(得分:2)

因此,首先,假设这是Express,没有理由(或要求)从中间件返回Promise,则忽略返回值。其次,您当前的代码实际上将导致有效请求挂起,因为您没有调用next将请求传播到下一个中​​间件。

考虑到这一点,您的中间件应该看起来更像

validateRequest: (req, res, next) => {
  if (!req.body.title || !req.body.location || !req.body.description || !req.body.author) {
    // end the request
    res.status(errCode.invalid_input).json({
      message: 'Invalid input'
    });
  } else {
    // process the next middleware
    next();
  }
},

基于上述内容,有效的单元测试应类似于

test('create.validateRequest should throw error if incorrect user inputs', () => {
  const next = jest.fn();
  const req = httpMocks.createRequest({ 
    body: { 
      title: 'A new world!',
      location: '...bunch of talks...',
      description: '...'  
    }
  });
  const res = httpMocks.createResponse();
  validateRequest(req, res, next);
  // validate HTTP result
  expect(res.statusCode).toBe(400);
  expect(res._isJSON()).toBeTruthy();
  // validate message
  const json = JSON.parse(res._getData());
  expect(json.message).toBe('Invalid input');
})