Reputation: 2625
Could anybody suggest me a way how to mock $resource
object
I've searched though internet, but all my tries were finished by KARMA testing. I don't need it.
My idea is to have just fake object, so I will be able to switch between $resource
implementations in my app.
Thanks.
Upvotes: -1
Views: 316
Reputation:
This plunk shows how I go about mocking resource objects, from a angular service, in a controller. I use SinonJs to fake a resource object. Then I basically fake the promise chain by injecting $q.
To fake the promise chain you need to get a defer object from $q, then get a promise from it.
In your tests, you then either fake a success or a failure by calling promise.resolve()
or promise.reject()
on that promise. You can fake data from the server by passing an object in as a parameter like this promise.reject(someData)
.
You then have to make sure that you scope.apply()
. To make sure that whatever it is you wanted to do becomes visible on scope.
I'm not entirely sure if this is the right way to go about this, but it has been working for me.
Upvotes: 1
Reputation: 35920
dskh presented one way to do it. Here's a another way which you might find to be easier... although it's ofen used for unit testing, you can use angular-mocks.js in your app as well:
app.run(function($httpBackend) {
$httpBackend.whenPOST('/string/match/url').respond(function (method, url, data) {
return [{some:data}];
});
$httpBackend.whenGET(/regexpmatch/).respond(function (method, url, data) {
return {some:{other:data}};
});
// pass through other stuff
$httpBackend.whenPOST(/.*/).passThrough();
$httpBackend.whenGET(/.*/).passThrough();
$httpBackend.whenDELETE(/.*/).passThrough();
$httpBackend.whenJSONP(/.*/).passThrough();
$httpBackend.whenPUT(/.*/).passThrough();
});
Upvotes: 1
Reputation: 3268
You can use $provide to do this.
angular.module(“MyApp”,[])
.config([“$provide”,function($provide){
$provide.decorator(“$resource”,function($delegate, myReplacementResource){
//$delegate is the original $resource, if you just want to modify it
//either inject a replacement resource that you have already registered
//as a factory (recommended). Or make it here.
return myReplacementResource;
});
}])
Upvotes: 1