ritmatter ritmatter - 6 months ago 35
Javascript Question

Jasmine have createSpy() return mock object

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.

Answer

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().andCallFake(function(msg) { return this });