小编Rya*_*yan的帖子

是否可以为 Node.js fs.readFile() 编写 Jest 单元测试?

我是 Jest 单元测试的新手,想知道 Jest 是否可以用于测试 Node.js 文件系统模块。

\n\n

我目前有一个包含一首短诗的文本文件,viewText 功能控制台将这首诗记录在我的终端上。

\n\n

使用 Jest,我的目标是编写一个测试来检查viewText函数是否确实正常工作。

\n\n
const viewText = () => {\n  fs.readFile('poem.txt', 'utf8', (err, data) => {\n    if (err) throw err;\n    console.log(data);\n  });\n};\n
Run Code Online (Sandbox Code Playgroud)\n\n

对于 Jest,我尝试过:

\n\n
jest.spyOn(global.console, 'log');\n\nconst mockPoem = 'Some say the world will end in fire, Some say in ice. From what I\xe2\x80\x99ve tasted of desire I hold with those who favor fire ... And would suffice.';\n\ndescribe('viewText', () => {\n  const mockReadFile = jest.fn();\n  mockReadFile.mockReturnValue(mockPoem);\n\n  it('prints …
Run Code Online (Sandbox Code Playgroud)

javascript unit-testing node.js jestjs

7
推荐指数
1
解决办法
1万
查看次数

标签 统计

javascript ×1

jestjs ×1

node.js ×1

unit-testing ×1