And*_* D_ 2 unit-testing backend node.js express jestjs
我正在尝试学习如何在express.js 上运行 Jest 测试,但收到此错误
Run Code Online (Sandbox Code Playgroud)TypeError: express.json is not a function
但是,如果我注释掉 index.js 中的这两行:
app.use(express.json({limit: '50mb'}));
app.use(express.urlencoded({limit: '50mb', extended: true}));
Run Code Online (Sandbox Code Playgroud)
然后它就会工作并通过前两个测试。我该如何修复这个错误?
你没有嘲笑这个express.json
方法。
例如
\nindex.js
:
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)\nindex.test.js
:
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
归档时间: |
|
查看次数: |
812 次 |
最近记录: |