node.js - 当 express 应用程序位于函数内部时,如何在 nodejs 中模拟 express?
问题描述
我有httpListener.ts
,看起来像这样:
export function startListening() {
const app = express();
app
.use(bodyParser.json())
.post('/home/about', func1)
.get('/user/product/:id', func2)
.use(function (req, res) {
res.status(404).send(`no routing for path ${req.url}`);
})
.listen(httpListenerConfig.port, () => {
console.log('listening..');
});
}
我必须为func1
and编写单元测试func2
(这些函数是私有的),我想使用假 http 请求来调用它们。
任何想法?
解决方案
您可以使用 superTest 之类的框架来测试 http 请求。SuperTest 需要 express 应用程序,因此我正在导出该应用程序。我将 app.listen 分配给服务器,以便在测试后关闭服务器(server.close)。
httpListener.js
var express = require('express');
function startListening() {
const app = express();
app
.get('/home/about', func1)
.get('/user/product/:id', func2)
.use(function (req, res) {
res.status(404).send(`no routing for path ${req.url}`);
})
var server = app.listen(3001, () => { //so the server can be closed after the test
console.log('listening..');
});
module.exports = server;
}
function func1 (req, res) {
res.status(200).send('this is home - about page');
}
function func2 (req, res) {
res.status(200).send('this is product page');
}
startListening();
httpListener-test.js
var request = require('supertest');
describe('loading express', function () {
var server;
beforeEach(function () {
server = require('./httpListner.js');
});
afterEach(function () {
server.close();
});
it('responds to /home/about', function test(done) {
request(server)
.get('/home/about')
.expect(200) //test status
.expect('this is home - about page', done); //test the response string
});
});
要在 func1 和 func2 上进行更多测试,您必须将它们导出以便可以进行测试。
推荐阅读
- reactjs - 从 props React 计算索引值时出错(硬编码时有效)
- python - 检查失败:vec.size() == NDIMS (1 vs. 2) RaspberryPi 卷积神经网络中的中止错误
- python - 尝试循环后我的字典为空
- vb6 - vb6.0中所有字符输入之间的距离
- python - 这本书[Learning Python]声称范围是一个生成器--这是一个错误的陈述吗?
- python - 我打算写一个测验程序,当答案正确时加分,在python中给出错误答案时扣分
- time - 如何在某个小时标记运行 Lua 脚本?
- apache-flink - Flink Map 函数具有多并行性,以及如何确定最终 sink 的顺序
- jboss - Jboss EAP 7.1 ServiceModuleLoader 返回 null
- google-cloud-dataflow - 数据流作业似乎被卡住了,因为在过去 1 小时内没有看到任何工作人员活动