3

我正在尝试使用 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}}]
  })
4

1 回答 1

4

根据此Nock 文档,您可以在回复中返回 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);
于 2016-03-05T20:04:51.340 回答