Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override mocked response of $httpBackend in Angular?

Is is possible to override or re-define mocked response in mocked $httpBackend?

I have test like this:

beforeEach(inject(function ($rootScope, $controller, _$httpBackend_) {   $httpBackend = _$httpBackend_;    //Fake Backend   $httpBackend.when('GET', '/myUrl').respond({}); //Empty data from server   ...some more fake url responses...       } 

This is fine for most cases but I have few tests where I need to return something different for the same URL. But it seems that once the when().respond() is defined I can not change it afterwards in code like this:

Different response in a single specific test:

it('should work', inject(function($controller){   $httpBackend.when('GET', '/myUrl').respond({'some':'very different value with long text'})    //Create controller    //Call the url    //expect that {'some':'very different value with long text'} is returned   //but instead I get the response defined in beforeEach })); 

How do I do that? My code is now untestable :(

like image 671
David Votrubec Avatar asked Jul 25 '13 13:07

David Votrubec


2 Answers

The docs seem to suggest this style:

var myGet; beforeEach(inject(function ($rootScope, $controller, _$httpBackend_) {     $httpBackend = $_httpBackend_;     myGet = $httpBackend.whenGET('/myUrl');     myGet.respond({}); }); 

...

it('should work', function() {     myGet.respond({foo: 'bar'});     $httpBackend.flush();     //now your response to '/myUrl' is {foo: 'bar'} }); 
like image 167
trans1t Avatar answered Oct 10 '22 03:10

trans1t


Use a function in the respond, for example:

var myUrlResult = {};  beforeEach(function() {   $httpBackend.when('GET', '/myUrl').respond(function() {     return [200, myUrlResult, {}];   }); });  // Your test code here.  describe('another test', function() {   beforeEach(function() {     myUrlResult = {'some':'very different value'};   });    // A different test here.  }); 
like image 24
John Tjanaka Avatar answered Oct 10 '22 05:10

John Tjanaka