I'm having trouble testing streams (with jest) when there is a delay involved. I did try using fakeTimers as well, but to no avail. Any pointers would be appreciated.
I have coded the below to have no dependencies - so the code should run standalone The first of the two tests works, but the secod one fails.
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()
})
})
})
Aucun commentaire:
Enregistrer un commentaire