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.
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.
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.
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.
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").
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 });
this works for me:
const res = {
status: jasmine.createSpy('status').and.callFake(() => res),
send: jasmine.createSpy('send').and.callFake(() => res),
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With