使用nock模拟打开的Web套接字

时间:2015-07-19 19:14:58

标签: node.js websocket mocking nock

我正在尝试使用nock对针对Oanda的交易API编写的代码进行回溯测试。为此,我需要模拟流媒体价格API(请参阅http://developer.oanda.com/rest-practice/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}}]
  })

1 个答案:

答案 0 :(得分:3)

根据此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);