【问题标题】:How to mock a connection using nock library?如何使用 nock 库模拟连接?
【发布时间】:2019-06-25 02:37:33
【问题描述】:

我有验证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();
        });
    });
});

【问题讨论】:

  • 鉴于它是一个没有远程地址可参考的模拟请求,预期值是多少?
  • 在我的测试中,我想将其设置为本地 IP 并验证我的处理程序是否返回错误。

标签: node.js testing nock


【解决方案1】:

节点的http.ClientRequest.connectionaliassocket。当前版本的 Nock 没有正确设置 connection 别名(它是 recently fixed,但尚未发布),但是,它确实在 socket 属性上正确创建了一个虚拟套接字 shared between the request and the response .

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

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

【讨论】:

  • 如何从返回的 nock 范围访问我的测试中的请求?
  • 更新请求的方式/位置取决于测试设置本身。你能用你的测试的基本版本更新你的问题吗?请记住,Nock Scopes 并不直接指向请求。通常,您将创建请求作为测试的一部分。
猜你喜欢
  • 2017-10-17
  • 2015-10-08
  • 2017-07-24
  • 1970-01-01
  • 2016-06-09
  • 2021-05-31
  • 2015-08-05
  • 2020-09-02
  • 2015-12-16
相关资源
最近更新 更多