我真的在寻找最简单的方法来让我的angular应用程序使用模拟后端服务。
任何指针都会很棒,一个示例应用程序展示了如何编写一个简单的应用程序,并使用它来完成这项工作。tnx!
发布于 2013-02-20 15:57:12
以下是一个使用$httpBackend的示例的sample plunkr,该示例使用无后端开发作为回答this question的示例。
我添加到plnkr中以使其工作的主要内容包括:
angular-mocks.js文件。$httpBackend中第3行的ngMockE2E requires数组添加到了angular.module中,并添加了代码以告诉模拟后端在请求GET到特定$httpBackend时响应什么。这主要取自$httpBackend文档。请注意,您可以为任何想要实际到达后端的调用执行.passThrough() (绕过模拟)。如果后端的某些部分已经在工作,这一点尤其有用。
发布于 2015-02-12 10:26:53
以下是从各种示例中提取的基本模板:
'use strict';
(function() {
if( !document.URL.match(/\?nobackend$/) ){
// if not requested only add a blank stub to app dependency.
angular.module('ds.backendMock', []);
} else if (document.URL.match(/\?nobackend$/)) {
// if the query string is present add a module with a run definition to replace the back end.
angular.module('myMock', ['ngMockE2E'])
.run(function($httpBackend) {
// MOCK-RUNNER-CONFIGURATION-.
var DOMAIN = 'example.com',
$httpBackend.whenGET('http://'+DOMAIN+'/someexample')
.respond(
//MOCK-ERROR-STATUS-CODE
//401 //500 //404 //uncomment integer to mock status code and comment out mock data.
//MOCK-DATA-RESPONSE
{
'id' : '1',
'name' : 'MOCK',
'description' : 'mocking',
}
); //end mock.
// various passthroughs. these allow existing services to work, while some are mocked.
$httpBackend.whenGET('./some.html').passThrough();
// dont mock everything else, specify pass through to avoid error.
$httpBackend.whenGET(/^\w+.*/).passThrough();
$httpBackend.whenPOST(/^\w+.*/).passThrough();
});
}
})(angular);https://stackoverflow.com/questions/14949932
复制相似问题