【问题标题】:mocking fs.existsSync inside Express controller with Jest用 Jest 在 Express 控制器中模拟 fs.existsSync
【发布时间】:2021-05-01 10:01:38
【问题描述】:

`问题:

我只想为特定控制器模拟 fs.existsSync()。以下面的方式执行此操作 - 在控制器之外的全局方法上应用模拟。这会导致测试失败(因为existsSync 函数在应用程序的不同位置使用)。

在我的 Express 控制器中,我有以下内容:

const fs = require('fs')

export default async (req: Request, res: Response, next: NextFunction) => {
   ...
   if (!fs.existsSync(htmlTemplate)) {
      return next(new ServerError(500, ResponseMessages.ss_error_template_not_rendered))
   }
   ...
}

在我使用 Jest 进行的相应超测中,我得到了:

  const _fs = fs.existsSync
  const mockedExistSync = jest.fn().mockImplementation((file: any) => {
    return false
  })
  fs.existsSync = mockedExistSync
  await request(app.server)... // and so on...
  fs.existsSync = _fs // restore to the original

我不会在测试中的任何地方做jest.mock(...)。就是这个。

有没有更好或有效的方法来解决这个问题?

【问题讨论】:

  • ` = jest.fn()` 是一种糟糕的做法,重新分配会永久破坏原始实现。在您的情况下,失败的测试将导致测试交叉污染,因为 fs.existsSync = _fs 无法执行。使用 jest.spyOn 来模拟方法和访问器,在 beforeEach 中对其他属性使用重新赋值以无条件地恢复原始值。

标签: node.js unit-testing jestjs mocking


【解决方案1】:
import fs from 'fs';
const spy = jest.spyOn(fs, 'existsSync').mockImplementation();

【讨论】:

    猜你喜欢
    • 2020-07-14
    • 2020-10-19
    • 2019-04-21
    • 1970-01-01
    • 1970-01-01
    • 2022-11-12
    • 1970-01-01
    • 2020-09-02
    • 2019-10-07
    相关资源
    最近更新 更多