Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

189
Views
How to create a broken stream for a test?

I have this function and I want to test it. I want to test stream.on('error', err => reject(err)); line, but don't know how to reach it. What could I input in this function to trigger the error throw? Thank you!

function streamToString(stream) {
  const chunks = [];
  return new Promise((resolve, reject) => {
    stream.on('data', chunk => chunks.push(Buffer.from(chunk)));
    stream.on('error', err => reject(err));
    stream.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
  });
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

If you are in nodejs and using jest you could Emit the error by your self like:


function streamToString(stream) {
  const chunks = [];
  return new Promise((resolve, reject) => {
    stream.on("data", (chunk) => chunks.push(Buffer.from(chunk)));
    stream.on("error", (err) => reject(err));
    stream.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
  });
}

test("broken stream", () => {
  let fs = require("fs");
  let stream = fs.createReadStream("file.txt");
  let res = streamToString(stream);
  stream.emit("error", "OH NO!");
  return expect(res).rejects.toMatch("OH NO!");
});

//or

test("broken stream", () => {
  let fs = require("fs");
  let stream = fs.createReadStream("file.txt");
  let res = streamToString(stream);
  stream.destroy("OH NO!");
  return expect(res).rejects.toMatch("OH NO!");
});

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!