如何在节点中创建请求和响应对象

Seá*_*yes 6 unit-testing node.js express nock

我正在尝试为我的节点/快速处理程序模拟请求和响应对象。我尝试了一些模拟库,但遇到了 API 兼容性问题,这使得它们对于测试目的来说太不可靠。

我想做的是自己创建原始请求和响应对象,并将输出定向到实时连接之外的其他地方。

这是我到目前为止所拥有的:

env.mockReq = function(o){
    o = o || {};
    o.hostname = 'www.tenor.co';
    o.protocol = 'https';
    o.path = o.url;
    o.createConnection = function(){
        console.log('mockReq createConnection');
    };
    var req = new http.ClientRequest(o);
    req.url = o.url;
    req.method = o.method;
    req.headers = o.headers || {};
    return req;
};
env.mockRes = function(o){
    var res = new http.ServerResponse({
        createConnection: function(){
            console.log('mockRes createConnection');
        }
    });
    return res;
};
Run Code Online (Sandbox Code Playgroud)

这是一些测试代码:

var req = env.mockReq({method: 'GET', url: '/'});
var res = env.mockRes();


res.on('end', function(arguments){
    expect(this.statusCode).toBe(200);
    expect(this._getData().substr(-7)).toEqual('</html>');
    scope.done();
    done();
});

// my express app
app.handle(req, res);
Run Code Online (Sandbox Code Playgroud)

我的处理程序正在将流数据源传输到响应:

stream.pipe(response);
Run Code Online (Sandbox Code Playgroud)

当我在浏览器中加载请求时,它工作正常,但我的测试超时,因为响应end事件永远不会被触发。我应该注意到,我的处理程序中有正在测试的日志语句,并且它会一直完成到最后。

让事情变得复杂的是,我使用 nock 来模拟一些 API 请求。我必须添加以下内容以防止出现错误:

// Prevents "Error: Protocol "https" not supported. Expected "http:""

nock('http://www.example.com')
.persist()
.get('/non-existant-path')
.reply(function(uri, requestBody) {
    console.log('nock path:', this.req.path);
    return ''
});
Run Code Online (Sandbox Code Playgroud)

但 nock 回调实际上从未被调用。但如果没有这段代码,即使我不使用 https,我也会收到该错误。我网站的实时版本将所有流量重定向到 https,因此可能正在建立实时连接,但是为什么我的处理程序正在执行?