【问题标题】:Covering function inside callback function with jest用玩笑覆盖回调函数内的函数
【发布时间】:2019-02-22 01:37:05
【问题描述】:

我正在开发一个 Nodejs 应用程序。我正在使用静音来上传文件。当我用 jest 编写单元测试时,我看到测试覆盖范围内的函数。它表明我已经发现了线条。问题是这些函数是构造函数选项中的辅助函数

const storage = multer.diskStorage({
  destination: "uploads/",
  filename: (req, file, cb) => {
    filterFilename(req, file, cb);
  }
});
const upload = multer({
  storage: storage,
  limits: {
    files: 2,
    fileSize: 5 * 1024 * 1024
  },
  fileFilter: (req, file, cb) => {
    checkFileType(file, cb);
  }
});

我想知道如何测试filterFilenamecheckFileType 函数以及其中的语句。顺便说一下,这些函数是私有函数。我不想导出它们。

【问题讨论】:

    标签: node.js unit-testing jestjs


    【解决方案1】:

    测试此代码的一种方法是像这样模拟multer

    var multer  = require('multer')
    jest.mock('multer', () => jest.fn())
    
    test('basic', () => {
      runTheCodeInYourSnippet();
      expect(multer).toHaveBeenCalled()
      const {
        storage,
        fileFilter
      } = multer.mock.calls[0][0]
    
      // test storage.filename(req, file, cb)
      // and fileFilter(req, file, cb)
    })
    
    

    【讨论】:

      猜你喜欢
      • 2021-12-09
      • 1970-01-01
      • 1970-01-01
      • 2010-10-25
      • 2018-12-07
      • 1970-01-01
      • 2020-12-16
      • 1970-01-01
      • 2014-10-03
      相关资源
      最近更新 更多