rest - 使用 Grunt 模拟端点

标签 rest angularjs mocking gruntjs yeoman

我正在使用 Yeoman、Grunt 和 Bower 来构建一个平台,用于构建独立于后端的前端。我的想法是我的所有(AngularJS) Controller 、服务、工厂等都存在于这个项目中,然后根据 grunt 构建的结果注入(inject)到我的服务器端代码库中。

我的问题是:

如何模拟端点,以便 Grunt 服务器响应与我的(Rails)应用程序相同的端点?

目前我正在使用:

 angular.module('myApp', ['ngResource'])

 .run(['$rootScope', function ($rootScope) {
     $rootScope.testState = 'test';
  }]);

然后在我的每一项个人服务中:
   mockJSON = {'foo': 'myMockJSON'}

在每种方法上:
   if($rootScope.testState == 'test'){
    return mockJSON;
  }
  else {
    real service logic with $q/$http goes here
  }

然后在 grunt build 之后, testState = 'test'被移除。

这显然是一个相对笨拙的架构。我怎样才能避免它?如何让 Grunt 响应与我的应用程序相同的端点(其中一些具有动态参数)应用一些逻辑(如果需要),并提供一个 json 文件(可能取决于路径参数)?

最佳答案

我已经通过使用 express 编写一个以静态 json 响应的服务器来解决这个问题。

首先,我在我的项目中创建了一个名为“api”的目录。在该目录中,我有以下文件:
package.json :

   {
     "name": "mockAPI",
     "version": "0.0.0",
     "dependencies": {
        "express": "~3.3.4"
      }
   }

然后我运行 npm install在这个目录中。
index.js :
    module.exports = require('./lib/server');
lib/server.js :
    express = require('express');
    var app = express();

    app.get('/my/endpoint', function(req, res){
        res.json({'foo': 'myMockJSON'});
   });

    module.exports = app

最后在我的全局Gruntfile.js :
         connect: {
            options: {
               port: 9000,
               hostname: 'localhost',
            },
            livereload: {
              options: {
                 middleware: function (connect, options) {
                   return [
                     lrSnippet,
                     mountFolder(connect, '.tmp'),
                     mountFolder(connect, yeomanConfig.app),
                     require('./api')
                   ];
               }
            }
         },

然后服务发出请求, express 服务器提供正确的 JSON。

之后 grunt build , express 服务器被一个 rails 服务器简单地替换。

关于rest - 使用 Grunt 模拟端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17934608/

相关文章:

angularjs - 向 ui.select angular 上的 Controller 发送数据

javascript - ScrollView 不随表面 fa-size 滚动 [未定义,true]

c# - Rhino Mocks 部分模拟

c# - 无法加载文件或程序集 'Microsoft.AI.Web' 或其依赖项之一。该系统找不到指定的文件

node.js - Paypal :使用 REST API/Nodejs SDK 的交易历史

c# - 在 WCF Rest 端点中使用参数 "params string[]"

javascript - 使用 Angularfire 从 Firebase 获取特定键的数组

java - 为什么我得到 org.codehaus.jackson.map.JsonMappingException : No suitable constructor found for type

entity-framework - EF4 - 可以模拟 ObjectContext 进行单元测试吗?

java - 如何在对模拟的不同调用中返回不同的值?