Javascript: How to look into the superspy with jasmine?

I am using the ajax super agent library for the application, and I am trying to write some unit tests for it. I have a class that looks like this:

someClass = { getData: function(){ _this = this; superagent.get('/some_url').end(function(res){ if(res.body){ _this.data = res.body } }); }); } 

How to write a Jasmine test to test for a call to _this.data = res.body ? Setting up a spy with and.callThrough() on getData does not work. I do not want to name the corresponding URL; I am just trying to verify that if he receives data, he is doing something with it.

thanks

+7
ajax unit-testing jasmine superagent
source share
4 answers
 spyOn(superagent, 'get').and.callFake(function(url) { return { end: function(cb) { //null for no error, and object to mirror how a response would look. cb(null, {body: data}); } } }); 
+2
source share

Bror's answer works fine. To add something to his answer, when we need to add another super agent function (like set ) to the spyOn method, you can use the following.

 spyOn(superagent, 'get').and.callFake(function(url) { return { set: function() { return { end: function(cb) { //null for no error, and object to mirror how a response would look. cb(null, {body: data}); } } } }); 

Here, the set function is used to set headers in a request.

0
source share

There is another good solution here, which is to abstract the anonymous function:

 someClass = { getData: function(){ _this = this; superagent.get('/some_url').end(this.handleAjax); }, handleAjax: function(res){ if(res.body){ _this.data = res.body } } } 

Now you can test the handleAjax function discretely and with simple tests; as well as the superspy stub, since you only need to check the .end() method is called on it with a specific value.

Anonymous functions are problematic for other reasons than just testing, so this is a good refactoring

0
source share

Say it's a patch, first enter the patch patch return value:

 this.mockPatchObject = { set: () => { return { end: (cb: any) => { cb(null, {body: 'etc'}); }, }; }, }; 

then return it as the value of the patch:

 this.superagentSpy = spyOn(request,'patch').and.returnValue(this.mockPatchObject); 

then look at the set function of the mock patch object:

 this.superagentSetSpy = spyOn(this.mockPatchObject, 'set'); 
0
source share

All Articles