如何使用Nock库模拟连接



我的应用程序代码验证 response.connection.remoteAddress不是本地IP,但是当使用nock response.connection只是一个没有 remoteAddress属性的eventemitter实例。我如何修改nock产生的响应?

更新:我最终嘲笑Isprivate((:

it('GET returns a 403 status code when example.com resolved to internal ip', function(done){
    const scope = nock('https://example.com')
    .get('/some/fetched/url')
    .replyWithFile(200, FILE_CONTENT);
    spyOn(ip, 'isPrivate').and.callFake(() => {
        return true;
    });
    // this handler fetches a url, we want to throw an error if it
    // resolves to an internal IP
    fetch(`${env.testHost}/some-url-under-test`).then(function(response){
        response.text().then(function(body){
            scope.done();
            expect(response.status).toBe(403);
            expect(body).toEqual('Forbidden');
            done();
        });
    });
});

节点的http.ClientRequest.connectionsocket的别名。Nock的当前版本未正确设置connection别名(最近是修复的,但尚未发布(,但是,它确实会正确创建一个虚拟套接字,该插座在请求和socket属性上的响应之间共享。

请记住,虚拟Socket对象没有远程remoteAddress属性,但是您应该能够在创建请求和调用end之间添加一个。

req.socket.remoteAddress = '127.0.0.1'
req.end()

最新更新