unit-testing - 尝试使用 Jest 模拟 fs.readFileSync 时出错
问题描述
这是我的测试文件:
const request = require('supertest');
const app = require('../../src/app');
const fs = require('fs');
jest.mock('fs');
describe('Get Accounts Info', () => {
it('Get Accounts Info', async () => {
fs.readFileSync.mockResolvedValue({ message: 'Test'})
const res = await request(app).get('/accounts')
});
});
但是,当我尝试运行 by:npm test -- routes.test.js -t "Get Accounts Info"
时,会出现错误:
<--- Last few GCs --->
[20668:0000020C15EF9CD0] 82511 ms: Mark-sweep (reduce) 2047.1 (2050.7) -> 2046.4 (2051.9) MB, 4231.6 / 0.0 ms (+ 0.0 ms in 2 steps since start of marking, biggest step 0.0 ms, walltime since start of marking 4232 ms) (average mu = 0.113, current mu = [20668:0000020C15EF9CD0] 88662 ms: Mark-sweep (reduce) 2046.7 (2050.9) -> 2046.5 (2052.2)
MB, 5331.4 / 0.0 ms (+ 0.0 ms in 5 steps since start of marking, biggest step 0.0 ms, walltime since start of marking 6150 ms) (average mu = 0.124, current mu =
<--- JS stacktrace --->
FATAL ERROR: MarkCompactCollector: young object promotion failed Allocation failed - JavaScript heap out of memory
1: 00007FF7BD3A4C6F napi_wrap+111007
2: 00007FF7BD3481F6 v8::base::CPU::has_sse+59910
3: 00007FF7BD3490F6 node::OnFatalError+294
4: 00007FF7BDC2220E v8::Isolate::ReportExternalAllocationLimitReached+94
5: 00007FF7BDC06FDD v8::SharedArrayBuffer::Externalize+781
6: 00007FF7BDAB011C v8::internal::Heap::EphemeronKeyWriteBarrierFromCode+1516
7: 00007FF7BDA9AB9B v8::internal::NativeContextInferrer::Infer+59739
8: 00007FF7BDA7FE6F v8::internal::MarkingWorklists::SwitchToContextSlow+56975
9: 00007FF7BDA93B5B v8::internal::NativeContextInferrer::Infer+31003
10: 00007FF7BDA8AC3D v8::internal::MarkCompactCollector::EnsureSweepingCompleted+6285
11: 00007FF7BDA92DAE v8::internal::NativeContextInferrer::Infer+27502
12: 00007FF7BDA96DFB v8::internal::NativeContextInferrer::Infer+43963
13: 00007FF7BDAA07F2 v8::internal::ItemParallelJob::Task::RunInternal+18
14: 00007FF7BDAA0781 v8::internal::ItemParallelJob::Run+641
如何修复或模拟fs.readFileSync
?
解决方案
我更喜欢只模拟我将要使用的方法,如下所示;
jest.spyOn(fs, 'readFileSync').mockImplementation(function () {
// Whatever you want to return. In your case, maybe a promise.
});
推荐阅读
- spring - Spring JPA 双向关系
- api - Google 日历和 Looker 集成
- flutter - 使用 graphql_flutter 连接到 Graphql API 时出错
- testing - 如何动态生成 bazel 测试套件?
- dialogflow-es - 如果您只知道显示名称,那么检索 DialogFlow Intent 的 Id 的最佳 API 调用是什么?
- java - 为什么 System.getenv() 从 .bat 文件运行时返回 null?
- python - 类型错误:predict() 缺少 1 个必需的位置参数:'X'
- javascript - 如何在 javascript 中返回变量之前将 navigator.geolocation.getCurrentPosition() 中的纬度和经度存储到变量中
- excel - Excel Online:在同一行中的单元格更改时添加时间戳
- php - ACF 排序问题