我如何 return 模拟从请求到 Node 中的 Twitter Streaming API 的数据

How do I return mock data from requests to the Twitter Streaming API in Node

我有一个连接到 Twitter REST 和流式传输 API 的节点应用程序。为了测试向 REST API 发出请求的代码,我可以使用 Nock 来拦截 HTTP 请求和 return 模拟数据,如下所示:

var nock = require('nock')

var mockData = [...]

nock('https://api.twitter.com/1.1')
.get('/search/tweets.json')
.reply(200, mockData)

我的应用程序还连接到流 API 端点 statuses/filter and performs some analysis on tweets received via the streaming API. In Nock's README 它声明您可以将函数传递给 .query() return 是一个流,但是我没有无法使它正常工作。

我如何 return 使用 Nock(或其他库,如有必要)模拟从请求到此端点的数据?理想情况下,我希望能够在需要时将推文发送到测试流中,例如:

it('should correctly process tweets coming in on the streaming API', () => {
    var mockTweet = {...}

    sendMockTweetToStream(mockTweet)

    ...verify that the mock tweet was received and processed

})

我在测试中找到了一种无需模拟流式传输的方法 API。

我正在使用 NPM Twitter package 访问 Twitter 流式传输 API,如下所示:

var client = new Twitter({
  consumer_key: twitterConsumerKey,
  consumer_secret: twitterConsumerSecret,
  access_token_key: twitterAccessTokenKey,
  access_token_secret: twitterAccessTokenSecret
})

stream = client.stream('statuses/filter', {track: 'something'})

stream.on('data', event => {
  // Do some processing of incoming tweets here
})

我没有模拟流 API,而是使用我自己的带有 rewire 的流来模拟 client 对象,并设置了一个函数以允许我随时向它发送模拟推文。

const rewire = require('rewire')
const stream = rewire('stream')
const moduleToTest = require('somemodule')

const mockStream = new stream.Readable()
mockStream._read = () => {}
mockStream.destroy = () => {}

// Send a Tweet event to the mock stream
function writeTweetToStream (text) {
  mockStream.emit('data', {text: text})
}

describe('Module that uses the Twitter Streaming API', () => {
  beforeAll(() => {
    // client.stream should return our mock stream
    moduleToTest.__set__('client', {stream: () => { return mockStream }})
  })

  it('should process incoming tweets', () => {
    writeTweetToStream('This is a tweet #somehashtag')

    // Assert that the tweet was received and processed
  })
})