gpt4 book ai didi

node.js - 使用 Jest 测试 Express 时,有办法修复此 "TypeError: express.json is not a function"吗?

转载 作者:行者123 更新时间:2023-12-03 08:34:44 24 4
gpt4 key购买 nike

我正在尝试学习如何在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}));

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

Here the index.js

and here the 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

关于node.js - 使用 Jest 测试 Express 时,有办法修复此 "TypeError: express.json is not a function"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64259504/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com