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 :(
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'} });
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. });
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