在使用 Jest 测试 Express 时,有没有办法解决此问题"TypeError: express.json is not a function"?



我正试图学习如何在express.js上运行Jest测试,但我收到了这个错误

TypeError: express.json is not a function 

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

app.use(express.json({limit: '50mb'}));
app.use(express.urlencoded({limit: '50mb', extended: true}));

那么它就会工作并通过前两次测试。如何修复此错误?

这里是index.js

这里是index.test.js

您没有模拟express.json方法。

例如

index.js:

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

index.test.js:

const express = require('express');
const useSpy = jest.fn();
const listenSpy = jest.fn();
const urlencodedMock = jest.fn();
const jsonMock = jest.fn();
jest.mock('express', () => {
return () => ({
listen: listenSpy,
use: useSpy,
});
});
express.json = jsonMock;
express.urlencoded = urlencodedMock;
describe('64259504', () => {
test('should initialize an express server', () => {
require('./index');
expect(jsonMock).toBeCalled();
expect(urlencodedMock).toBeCalled();
expect(listenSpy).toHaveBeenCalled();
});
test('should call listen fn', () => {
require('./index');
expect(jsonMock).toBeCalled();
expect(urlencodedMock).toBeCalled();
expect(listenSpy).toHaveBeenCalled();
});
});

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

PASS  src/stackoverflow/64259504/index.test.js (13.203s)
64259504
✓ should initialize an express server (626ms)
✓ should call listen fn (1ms)
----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |       75 |       50 |        0 |       75 |                   |
index.js |       75 |       50 |        0 |       75 |          13,14,16 |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        15.01s

最新更新