javascript - 如何测试简单的中间件

标签 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: ...

}

我在我的 route 使用它们,如下所示:

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 输出:
错误
无效

Question: How can I test this validateRequest middleware?

最佳答案

首先,假设这是 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');
})

关于javascript - 如何测试简单的中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53572707/

相关文章:

node.js - 如何获取正在运行的 Node.js 进程的线程转储?

java - 我对派生类的单元测试是否应该继承对父类(super class)的测试?

c# - 模拟 IJSRuntime 以进行 Blazor 组件单元测试

javascript - 使用动态创建的 DOM 元素在单击时添加样式

javascript - 在 AngularJs 中为转换器绑定(bind)双向两个输入

javascript - Amazon S3 JS SDK putBucketLifecycleConfiguration 给出 XML 架构错误

node.js - "PERMISSION_DENIED: Missing or insufficient permissions"当使用 google 云任务调用 firestore 函数时

javascript - 如何迭代生成器函数的结果

java - 将 NullPointerException 视为单元测试失败 : is it good practice?

javascript - Google Analytics 如何导出 PDF?