testing readable stream (in jest) with delay for pushed values
Asked Answered
L

0

6

I'm trying to create a Readable Stream where the data arrives in bursts with a delay in between packets (like in a networked read).

I'm having trouble testing this with jest. I have coded 2 tests below The first of the two tests works (in that it produces output to the console), but the second one fails - that is, no output is seen on the console. I did try using fakeTimers as well, but it seemed to make no difference. Any pointers would be appreciated.

The tests themselves have no dependencies - so the code should run standalone

const Readable = require('stream').Readable
function sleep(ms) {return new Promise(resolve => setTimeout(resolve, ms))}
const lines = ['line 1\n', 'line 2\nline 3']
function* getIter() {for (let line of lines) {yield line}}

describe ('Iteration', () => {

  it ('read iter values from stream', () => {
    let rs = new Readable, res, iter = getIter()

    while (res = iter.next()) {
      if (res.done) {
        rs.push(null)
        break
      } else {
        rs.push(res.value)
      }
    }
    rs.pipe(process.stdout)
  })

  it ('read iter values from stream with delay', (done) => {
    var rs = new Readable,
        res,
        iter = getIter()

    while (res = iter.next()) {
      if (res.done) {
        sleep(1).then(() => {
          rs.push(null)
        })
        break
      } else {
        sleep(1).then(() => {
          rs.push(res.value)
        })
      }
    }

    sleep(10).then(() => {
      rs.pipe(process.stdout)
      done()
    })
  })
})
Latticework answered 13/2, 2018 at 13:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.