使用 Jest 测试 Express 时,有没有办法修复此“TypeError:express.json 不是函数”?

And*_* D_ 2 unit-testing backend node.js express jestjs

我正在尝试学习如何在express.js 上运行 Jest 测试,但收到此错误

TypeError: express.json is not a function 
Run Code Online (Sandbox Code Playgroud)

但是,如果我注释掉 index.js 中的这两行:

app.use(express.json({limit: '50mb'}));
app.use(express.urlencoded({limit: '50mb', extended: true}));
Run Code Online (Sandbox Code Playgroud)

然后它就会工作并通过前两个测试。我该如何修复这个错误?

这里是index.js

这里是index.test.js

sli*_*wp2 5

你没有嘲笑这个express.json方法。

\n

例如

\n

index.js:

\n
const express = require(\'express\');\nconst cors = require(\'cors\');\nconst app = express();\nconst corsOptions = {\n  origin: true,\n};\nconst PORT = process.env.PORT || 4002;\napp.use(cors(corsOptions));\napp.use(express.json({ limit: \'50mb\' }));\napp.use(express.urlencoded({ limit: \'50mb\', extended: true }));\n\napp.listen(PORT, (err) => {\n  if (err) {\n    console.log(\'Rumble in the Bronx! \' + err);\n  } else {\n    console.log(` <(Communications active at port http://localhost:${PORT}/)`);\n  }\n});\n
Run Code Online (Sandbox Code Playgroud)\n

index.test.js:

\n
const express = require(\'express\');\n\nconst useSpy = jest.fn();\nconst listenSpy = jest.fn();\nconst urlencodedMock = jest.fn();\nconst jsonMock = jest.fn();\n\njest.mock(\'express\', () => {\n  return () => ({\n    listen: listenSpy,\n    use: useSpy,\n  });\n});\n\nexpress.json = jsonMock;\nexpress.urlencoded = urlencodedMock;\n\ndescribe(\'64259504\', () => {\n  test(\'should initialize an express server\', () => {\n    require(\'./index\');\n    expect(jsonMock).toBeCalled();\n    expect(urlencodedMock).toBeCalled();\n    expect(listenSpy).toHaveBeenCalled();\n  });\n\n  test(\'should call listen fn\', () => {\n    require(\'./index\');\n    expect(jsonMock).toBeCalled();\n    expect(urlencodedMock).toBeCalled();\n    expect(listenSpy).toHaveBeenCalled();\n  });\n});\n
Run Code Online (Sandbox Code Playgroud)\n

带有覆盖率报告的单元测试结果:

\n
 PASS  src/stackoverflow/64259504/index.test.js (13.203s)\n  64259504\n    \xe2\x9c\x93 should initialize an express server (626ms)\n    \xe2\x9c\x93 should call listen fn (1ms)\n\n----------|----------|----------|----------|----------|-------------------|\nFile      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |\n----------|----------|----------|----------|----------|-------------------|\nAll files |       75 |       50 |        0 |       75 |                   |\n index.js |       75 |       50 |        0 |       75 |          13,14,16 |\n----------|----------|----------|----------|----------|-------------------|\nTest Suites: 1 passed, 1 total\nTests:       2 passed, 2 total\nSnapshots:   0 total\nTime:        15.01s\n
Run Code Online (Sandbox Code Playgroud)\n