20

I'm trying to mock up a response object, and it looks something like this:

var res = {
  status: jasmine.createSpy().andReturn(this),
  send: jasmine.createSpy().andReturn(this)
}

This returns the jasmine object. I'd really like to return the original res variable containing the mocked functions. Is that possible? I'm mainly implementing this to unit test functions containing res.status().send(), which is proving to be difficult.

ritmatter
  • 3,448
  • 4
  • 24
  • 43
  • Possible duplicate of [jasmine: spyOn(obj, 'method').andCallFake or and.callFake?](https://stackoverflow.com/questions/22041745/jasmine-spyonobj-method-andcallfake-or-and-callfake) – AncientSwordRage Nov 14 '18 at 10:24

2 Answers2

34

The answer here is actually pretty quick. Calling andReturn() will give you jasmine as 'this'. But, if you write andCallFake(), that function considers the mocked object to be this. Solution looks like so:

status: jasmine.createSpy().and.callFake(function(msg) { return this });
Francesco Borzi
  • 56,083
  • 47
  • 179
  • 252
ritmatter
  • 3,448
  • 4
  • 24
  • 43
10

this works for me:

const res = {
  status: jasmine.createSpy('status').and.callFake(() => res),
  send: jasmine.createSpy('send').and.callFake(() => res),
};
Olivier Torres
  • 101
  • 1
  • 2