如何创建模拟 http.ServerRequest 和 http.ServerResponse? [英] How to create a mock http.ServerRequest and http.ServerResponse?
问题描述
我为 http.Server
的 request 编写了一个处理程序事件(即带有签名的函数function (request, response) { ... }
),我想测试它.我想通过模拟 http.ServerRequest
和 http.ServerResponse
对象来做到这一点.我如何创建这些?
显而易见的方法似乎不起作用:
$ 节点>var http = require('http');>新的 http.ServerRequest();类型错误:未定义不是函数在回复:1:9...
我需要通过真正的"HTTP 服务器和客户端来测试吗?
至少有两个项目允许模拟 http.ServerRequest
和 http.ServerResponse
:
出于某种原因,通过真实的 HTTP 请求进行测试似乎更常见;https://github.com/flatiron/nock 似乎是这里使用的工具.>
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.com/howardabrams/node-mocks-http and https://github.com/vojtajina/node-mocks.
And for some reason it does seem to be more common to test via real HTTP request; https://github.com/flatiron/nock seems to be the tool to use here.
See also node.js: Mock http request and response.
这篇关于如何创建模拟 http.ServerRequest 和 http.ServerResponse?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!