作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试学习如何在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}));
然后它就会工作并通过前两个测试。我该如何修复这个错误?
最佳答案
您没有模拟 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/
我是一名优秀的程序员,十分优秀!