Mock backend for Angular / Gulp app

两盒软妹~` 提交于 2019-12-01 04:51:33

I recommend you check out https://github.com/wongatech/angular-multimocks. This allows you to create mock responses for your apis and allows you to switch between them in real time via the url in your app.

We originally created it where I work to solve this exact issue and it is now being used in multiple large tech companies in London.

You define each of your mocks like below, you can create multiple different response for a resource and then arrange them into scenarios. The file mockResources.json defines the available scenarios and describes which version of each resource should be used for each scenario.

Mock example:

{
  "httpMethod": "GET",
  "statusCode": 200,
  "uri": "/customer/cart",
  "response": {
    "id": "foo"
  }
}

Scenario Listing Example:

{
  "_default": [
    "root/_default.json",
    "account/anonymous.json",
    "orders/_default.json"
  ],
  "loggedIn": [
    "account/loggedIn.json"
  ]
}

It allows you to mock different rest verbs, different uris, add delays to responses (for either testing slow responses, or just too give you app a more live like feel).

It's a core part of our development and strongly integrated with our acceptance testing.

Checkout the demo @ http://tech.wonga.com/angular-multimocks, the project readme gives detailed instructions on setup happy to help with any further questions.

I went with json-server and gulp-json-srv which I think had some benefits of simplicity and quick setup.

gulpfile.js config to start json-server and to proxy the http calls using a "gulp mock" task:

gulp.task('mock', ['connect-mock'], function () {
    jsonServer.start({
        data: 'db.json',
        port: 8087
    });
});

gulp.task('connect-mock', function () {
    connect.server({
        port: 8085,
        livereload: true,
        middleware: function (connect, o) {
            return [(function () {
                var url = require('url');
                var proxy = require('proxy-middleware');
                var options = url.parse('http://127.0.0.1:8087');
                options.route = '/v2';
                return proxy(options);
            })()];
        }
    });
});

db.json with mocked data:

{
    "customers": [
        { "id": 1, "name": "Johnny B" },
        { "id": 2, "name": "Steve G" },
        { "id": 3, "name": "Glenn H" }
    ]

You can use mock server for this.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!