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

222
Views
Sinon: force callback call

I'm testing a function with this code:

return new Promise((ok, fail) => {
  this.repository.findById(id, (error, result) => {
    if (error)
      return fail(error);
    ok(result);
  });
});

I want to test the path of the fail, i.e., when the findById method calls the callback with an error. I'm using sinon to generate a stub for my repository and its findById method, but I don't know how to force the stub to call the callback with the desired parameters

Anybody did something like that before?

Thanks

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

With Sinon 2, you can use the callsFake method of a stub:

sinon.stub(repository, 'findById').callsFake((id, callback) =>
    callback(new Error('oops'))
);

See Sinon 2 documentation: http://sinonjs.org/releases/v2.1.0/stubs/

over 4 years ago · Santiago Trujillo Report

0

A more generic answer here: Every time I have to stub a callback, I do it like this

const stubFindId = sinon.stub(repository, 'findById');    
stubGetitem.callsFake((value: string, callback: any) => {
      return callback(true, false);
    });
over 4 years ago · Santiago Trujillo 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!