I'm developing an Angular app (actually, an Ionic app) that relies on a REST API. To communicate with the API, I will inject $resource
s into my controllers.
I want to focus on the app now, and worry about the backend later—so I'd like to create dummy versions of my various $resource
s. For example, my dummy Products
$resource will contain a few sample product records (hardcoded as JSON), and will support/mimic the same CRUD operations that the real $resource
will eventually support.
In other words, it will be similar to this —but will mimic the same API as $resource
(promises, error handling, etc.).
Obviously, I could roll my own solution to this—but surely this is already a solved problem. What's the standard approach?
(I've done a fair bit of Googling around this, but everything I find talks about unit testing and test frameworks—which I know little about. Anyway, that seems like a slightly different problem than the one I'm trying to solve. I've also seen a lot about $httpBackend
—but (1) that mocks the lower-level $http
service, not $resource
, which is what I need, and (2) it seems to be meant for use in the context of unit tests, which is not what I'm trying to do.)
I finally found an example of using $httpBackend
without a unit test .
Essentially, you can inject $httpBackend
into the run()
method of your module, like this:
app.run(function($httpBackend) {
var phones = [{name: 'phone1'}, {name: 'phone2'}];
$httpBackend.whenPOST('/phones').respond(function(method, url, data, headers){
console.log('Received these data:', method, url, data, headers);
phones.push(angular.fromJson(data));
return [200, {}, {}];
});
$httpBackend.whenGET('/phones').respond(function(method,url,data) {
console.log("Getting phones");
return [200, phones, {}];
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.