我正在开发一个大型 Angular 应用程序,它需要在浏览器中模拟整个 API(也称为无后端开发)。我的应用程序中会有很多不同的部分和 View ,每个部分和 View 都有自己的模拟定义。
我知道我可以使用 ngMock
模块的 $httpBackend
服务来模拟 AJAX 调用。这就是我想要的。我找到了 working snippet at jsfiddle .
但我缺少的是如何将其拆分为多个文件?正如我所说,我的应用程序将有数百个页面,甚至可能有更多 RESTful 资源,我不能简单地将其放入一个源文件中。这作为架构问题:将数千个 whenGET
和 whenPOST
调用划分到不同文件中的最佳方法是什么(有效、可扩展且易于维护)这将简单地模拟相同的 API? 如何根据项目文件结构分离模拟?应用程序中的每个模块是否应该有一个单独的 .run()
方法?我可以从 JSON 文件加载模拟吗?
我希望得到解释和演示
为了让回答更容易,下面是 fiddle 的相关部分:
myApp.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, {}];
});
$httpBackend.whenGET(/\.html$/).passThrough();
});
最佳答案
你可以这样使用:
XXXModule.factory('MockedDataProvider', () ->
getData: (url) ->
request = new XMLHttpRequest();
request.open('GET', url, false)
request.send(null)
request.response
)
.run([
'$httpBackend',
'MockedDataProvider'
($httpBackend, MockedDataProvider) ->
$httpBackend.whenGET(/i18n/).passThrough()
$httpBackend.whenGET('/api/xxx/yyy').respond(
(method, url, data) ->
data = MockedDataProvider.getData('xxx/mocked.json')
[200, data]
)
])
你可以将你的模拟分成不同的文件夹/模块等......它应该工作得很好:)
附言。代码在 cofffescript 中;)
关于javascript - Angular ngMock $httpBackend : split mocks into multiple files,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28920912/