【问题标题】:Simulate an open web socket with nock使用 nock 模拟打开的 Web 套接字
【发布时间】:2015-10-08 21:27:12
【问题描述】:

我正在尝试使用 nock 对针对 Oanda 交易 API 编写的代码运行回测。为此,我需要模拟流价格 API(请参阅 http://developer.oanda.com/rest-practice/streaming/ 的 Rates Streaming)。但是,似乎 nock 只允许您使用单个回复进行响应,即使响应是流。有什么方法可以发送数千个价格事件流作为对单个请求的单独响应?

var scopeStream = nock('https://stream-fxpractice.oanda.com')
  .persist()
  .filteringPath(function(path) {
    return '/stream';
  })
  .get('/stream')
  .reply(function(uri, requestBody) {
    return [200, {"tick":{"instrument":"AUD_CAD","time":"2014-01-30T20:47:08.066398Z","bid":0.98114,"ask":0.98139}}]
  })

【问题讨论】:

  • 蟋蟀 :-( 没有想法?
  • 请注意,nock 是关于“HTTP 服务器模拟”,而 WebSocket 协议不是 HTTP。可能您的意思是 Server-sent events 而不是 WebSockets。

标签: node.js websocket mocking nock


【解决方案1】:

根据Nock documentation,您可以在回复中返回 ReadStream。

我使用stream-spigot npm 包提出了以下示例(用于模拟 Marathon 事件流):

const nock = require('nock');

const EventSource = require('eventsource');
const spigot = require('stream-spigot');

let i = 0;

nock('http://marathon.com')
      .get('/events')
      .reply(200, (uri, req) => {
          // reply with a stream
          return spigot({objectMode: true}, function() {
              const self = this;
              if (++i < 5)
                  setTimeout(() => this.push(`id: ${i}\ndata: foo\n\n`), 1000);
          })
      });

const es = new EventSource('http://marathon.com/events');

es.onmessage = m => console.log(m);

es.onerror = e => console.log(e);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-07
    • 1970-01-01
    • 2017-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多