Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jasmine have createSpy() return mock object

Tags:

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.

like image 473
ritmatter Avatar asked Dec 28 '14 21:12

ritmatter


People also ask

How do you mock an object in Jasmine?

Using Jasmine spies to mock code Jasmine spies are easy to set up. You set the object and function you want to spy on, and that code won't be executed. In the code below, we have a MyApp module with a flag property and a setFlag() function exposed. We also have an instance of that module called myApp in the test.

How do you mock response in Jasmine?

When you want to mock out all ajax calls across an entire suite, use install() in a beforeEach . Because jasmine-ajax stubs out the global XMLHttpRequest for the page, you'll want to uninstall() in an afterEach so specs or setup that expect to make a real ajax request can. Make your requests as normal.

How do you use Jasmine createSpy?

Jasmine: createSpy() and createSpyObj() Jasmine's createSpy() method is useful when you do not have any function to spy upon or when the call to the original function would inflict a lag in time (especially if it involves HTTP requests) or has other dependencies which may not be available in the current context.

How do you make a spy house in Jasmine?

In Jasmine, you can do anything with a property spy that you can do with a function spy, but you may need to use different syntax. Use spyOnProperty to create either a getter or setter spy. it("allows you to create spies for either type", function() { spyOnProperty(someObject, "myValue", "get").


2 Answers

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 });
like image 122
ritmatter Avatar answered Sep 22 '22 20:09

ritmatter


this works for me:

const res = {
  status: jasmine.createSpy('status').and.callFake(() => res),
  send: jasmine.createSpy('send').and.callFake(() => res),
};
like image 37
Olivier Torres Avatar answered Sep 22 '22 20:09

Olivier Torres