如何创建模拟 http.ServerRequest 和 http.ServerResponse?

编程入门 行业动态 更新时间:2024-10-25 18:28:44
本文介绍了如何创建模拟 http.ServerRequest 和 http.ServerResponse?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我为 http.Server 的 request 编写了一个处理程序事件(即带有签名的函数function (request, response) { ... }),我想测试它.我想通过模拟 http.ServerRequesthttp.ServerResponse 对象来做到这一点.我如何创建这些?

显而易见的方法似乎不起作用:

$ 节点>var http = require('http');>新的 http.ServerRequest();类型错误:未定义不是函数在回复:1:9...

我需要通过真正的"HTTP 服务器和客户端来测试吗?

解决方案

至少有两个项目允许模拟 http.ServerRequesthttp.ServerResponse:https://github/howardabrams/node-mocks-http 和 https://github/vojtajina/node-mocks.

出于某种原因,通过真实的 HTTP 请求进行测试似乎更常见;https://github/flatiron/nock 似乎是这里使用的工具.>

另见 node.js:模拟 http 请求和响应.

I've written a handler for http.Server's request event (i.e. a function with signature function (request, response) { ... }) and I'd like to test it. I'd like to do this via mock http.ServerRequest and http.ServerResponse objects. How can I create these?

The obvious way doesn't seem to work:

$ node
> var http = require('http');
> new http.ServerRequest();
TypeError: undefined is not a function
    at repl:1:9
...

Do I need to test this via a "real" HTTP server and client?

解决方案

There's at least two projects that allow mocking of http.ServerRequest and http.ServerResponse: https://github/howardabrams/node-mocks-http and https://github/vojtajina/node-mocks.

And for some reason it does seem to be more common to test via real HTTP request; https://github/flatiron/nock seems to be the tool to use here.

See also node.js: Mock http request and response.

这篇关于如何创建模拟 http.ServerRequest 和 http.ServerResponse?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 22:13:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1401128.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:http   ServerRequest   ServerResponse

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!