loganhuskins
loganhuskins

Reputation: 1469

How to stub an async database call with sinon

I am trying to unit test the getAll method on this class:

module.exports = class BookController {
  static async getAll() {
    return await Book.query()
      .eager('reviews');
  }
};

Book is a Objection model.

How I'd like to test it is I want to fake the response from Book.query().eager() with my own data, since I can never verify what's in the database. For it to be a true unit test, should I just be testing that the Book.query() method is called? Or should I be testing that the returned data since that's the contract of the getAll() method? I'm really unsure how I should be stubbing this out.

Upvotes: 3

Views: 4987

Answers (1)

LostJon
LostJon

Reputation: 2387

With Sinon > 2.x, you can call .resolves() on your stub. I would do something like

var stub = sinon.stub(BookController, 'getAll');
stub.resolves({response:"ok"});
var bc = new BookController();
bc.getAll.then(function(data){
    expect(data.response).to.equal("ok");
    done();
},function(err){
    done("should NEVER get here");
});

Upvotes: 5

Related Questions