All Projects → mdasberg → ng-apimock

mdasberg / ng-apimock

Licence: MIT License
Node plugin that provides the ability to use scenario based api mocking: for local development for protractor testing

Programming Languages

typescript
32286 projects
javascript
184084 projects - #8 most used programming language
Gherkin
971 projects
HTML
75241 projects
Dockerfile
14818 projects

Projects that are alternatives of or similar to ng-apimock

angular2-cookie-law
Angular2+ component that provides a banner to inform users about cookie law
Stars: ✭ 38 (-62.75%)
Mutual labels:  angularjs, angular2
mock-data
Mock data in PostgreSQL/Greenplum databases
Stars: ✭ 115 (+12.75%)
Mutual labels:  mock, mock-data
fe-dev-server
FE Dev Server target to help frontend web developers create view template, styles and js easily.
Stars: ✭ 30 (-70.59%)
Mutual labels:  mock, mock-data
Fusebox Angular Universal Starter
Angular Universal seed project featuring Server-Side Rendering, @fuse-box bundling, material, firebase, Jest, Nightmare, and more
Stars: ✭ 132 (+29.41%)
Mutual labels:  angularjs, angular2
Angular4-seed
Angular 4 Seed for Angular Forms
Stars: ✭ 37 (-63.73%)
Mutual labels:  angularjs, angular2
Angular2 Express Mongoose Gulp Node Typescript
AngularJS 2 (Updated to 4.2.0) Mean Stack application which uses Angular2, Gulp, Express, Node, MongoDB (Mongoose) with Repository Pattern Business Layer
Stars: ✭ 201 (+97.06%)
Mutual labels:  angularjs, angular2
factory
Generate lots of mock API data with ease.
Stars: ✭ 17 (-83.33%)
Mutual labels:  mock, mock-data
Fef
The Front End Framework is a Thomson Reuters Tax and Accounting project to create a re-usable library for creating rich HTML based applications. The end goal is to assemble the publicly available libraries into a reference application with documentation along with best practice architecture.
Stars: ✭ 96 (-5.88%)
Mutual labels:  angularjs, angular2
percy-node
Utilities for visual regression testing in node based testing setups (like Protractor) for use with percy.io
Stars: ✭ 17 (-83.33%)
Mutual labels:  angularjs, protractor
router
Keep your Angular2+ router state in Redux
Stars: ✭ 28 (-72.55%)
Mutual labels:  angularjs, angular2
Blog
lizhonghui's blog
Stars: ✭ 109 (+6.86%)
Mutual labels:  angularjs, angular2
better-mock
Forked from Mockjs, Generate random data & Intercept ajax request. Support miniprogram.
Stars: ✭ 140 (+37.25%)
Mutual labels:  mock, mock-data
Clever Bootstrap 4 Admin Template With Angularjs Angular 2 Support
Clever is Boostrap 4 Admin Template with Angular 2 and AngularJS support
Stars: ✭ 98 (-3.92%)
Mutual labels:  angularjs, angular2
Angular5 Seed
Angular5 Seed for Application
Stars: ✭ 222 (+117.65%)
Mutual labels:  angularjs, angular2
Ion Digit Keyboard V2
A digital keyboard plugin to use in Ionic 2 applications.
Stars: ✭ 97 (-4.9%)
Mutual labels:  angularjs, angular2
interface-forge
Graceful mock-data and fixtures generation using TypeScript
Stars: ✭ 58 (-43.14%)
Mutual labels:  mock, mock-data
Angular Full Stack
Angular Full Stack project built using Angular, Express, Mongoose and Node. Whole stack in TypeScript.
Stars: ✭ 1,261 (+1136.27%)
Mutual labels:  angularjs, angular2
Angular2 Questionnaire
Angular Programming Book Part 3 Demo
Stars: ✭ 86 (-15.69%)
Mutual labels:  angularjs, angular2
laravel5Angular4
Laravel 5.4 & Angular 4.3.4
Stars: ✭ 37 (-63.73%)
Mutual labels:  angularjs, angular2
miz
🎯 Generate fake data, Just like a person.
Stars: ✭ 24 (-76.47%)
Mutual labels:  mock, mock-data

ng-apimock Build Status npm version dependency Status devDependency Status npm downloads

Node plugin that provides the ability to use scenario based api mocking:

  • for local development
  • for protractor testing

Plugins that use ng-apimock

MIGRATION to the new modular version

A new version of Ng-apimock has been released. This version has been refactored into multiple modules. You can find the migration guide here.

The functionality has been split up into the following modules:

Getting Started

npm install ng-apimock --save-dev

Once the plugin has been installed, you can require it with this line of JavaScript:

var ngApimock = require('ng-apimock')();

The "ngApimock" process mocks

Overview

In order to use the available mocks, you need to call the run function with this line of JavaScript:

ngApimock.run({
  "baseUrl": "http://<NODE_SERVER_API_URL>:<PORT>", // If not informed browser.baseUrl will be used
  "src": "test/mocks",
  "outputDir": "path/to/outputDir",
  "done": function() {
  // async
  }
});

The run function will process the mock data provided in the configuration and make it accessible for connect as middleware.

In order to watch for changes, you need to call the watch function with this line of Javascript:

ngApimock.watch("test/mocks");

The watch function will watch for changes in the mock directory and update accordingly.

Howto write mocks

There are a couple of rules to follow.

  1. For each api call create a separate file
  2. Each file needs to follow the format below.
{
  "expression": "your expression here (ie a regex without the leading and trailing '/' or a string)",
  "method": "the http method (ie GET, POST, PUT or DELETE)", // supports JSONP as well
  "body": "request body matcher (ie a regex without the leading and trailing '/' or a string)"  // optional
  "name": "identifiable name for this service call"  // if non is provided, expression$$method will be used
  "isArray": "indicates if the response data is an array or object",
  "responses": {
    "some-meaningful-scenario-name": {
      "default": true, // if false or not provided this response will not be used as default
      "status": 200, // optional - defaults to 200
      "headers": {}, // optional - defaults to {}
      "data": {}, // optional
      "file": "path/to/file.ext" // optional, when provided don't forget the matching content-type header as it will result in a file download instead of data
      "statusText": "", // optional
      "delay": 2000 // optional - defaults to no delay when provided this delay will only be used for this response
    },
    "some-other-meaningful-scenario-name": {
      "data": {}
    }
  }
}

Howto use global variables

If for instance, you have date sensitive information in you mocks, mock data is not flexible enough. You can use global variables for this. By surrounding a value in the response.data with %%theVariableName%%, you can make your data more flexible, like this:

"responses": {
    "some-meaningful-scenario-name": {
        "data": {
            "today": "%%today%%"
        }
    }
}

For local development you can use the web interface to add, change or delete variables. For protractor you can use the following commands

     ngApimock.setGlobalVariable(name, value); // to add or update
     ngApimock.deleteGlobalVariable(name); // to delete

Howto serve selected mocks

To be able to use the selected mocks you need to do two things:

  1. Add the connect middleware
  2. Add the mocking interface to your connect configuration

Add the connect middleware

When running connect you can do add the following middleware block to your configuration

var app = connect();
app.use(require('ng-apimock/lib/utils').ngApimockRequest);
app.use(function middleware2(req, res, next) {
  // middleware 2
  next();
});

Add the mocking interface to your connect configuration

When running grunt-contrib-connect you can do add the following staticServe block to your configuration

var app = connect();
app.use('/mocking', require('serve-static')('path/to/the/generated/mocking/index.html'));
app.use(function middleware2(req, res, next) {
  // middleware 2
  next();
});

Howto use for local development

As you have configured both the connect middleware and the mocking interface, everything should work out of the box. By default all the responses configured as default, will be returned if the expression matches.

If you would like to change the selected scenario, you can go to http://localhost:9000/mocking and use the interface to change the selected scenario or variables

The interface looks like this:

alt tag

Howto use for your protractor tests.

As you are building an AngularJS application you will probably use Protractor for testing your UI.

In order to use ngApimock in your protractor tests, require it in your protractor configuration like this:

exports.config = {
    onPrepare: function () {
        global.ngApimock = require('.tmp/mocking/protractor.mock.js');
    }
};

and from that point on you can use it in your tests

describe('Some test', function () {
    it('should do something', function() {
        ngApimock.selectScenario('name of some api', 'another'); // at runtime you can change a scenario
    });
 });

By default all the scenario's marked as default will be returned if the expression matches. So you only need to add ngApimock.selectScenario in case your test needs another scenario response to be returned.

NgApimock also works when running multiple tests concurrent, by using the protract session id of the test. This ensures that changing a scenario in one test, will not effect another test.

Using Angular 2 or higher with Protractor?

If you are using Angular 2 or higher in combination with Protractor you will need to add the following to you configuration.

Protractor 4

exports.config = {
    useAllAngular2AppRoots: true
};

Protractor 5 or higher

exports.config = {
    ngApimockOpts: {
        angularVersion: 2,  // {number} provide major version of Angular
        hybrid: false // optional boolean which can be used for testing Angular apps within an AngularJs app.
    }
};

Available functions

All these functions are protractor promises, so they can be chained.

selectScenario(name, scenarioName, options)

Selects the given scenario (when calling this function without a scenario or with 'passThrough' as scenario name, the call will be passed through to the actual backend)

delayResponse(name, delay)

Sets the delay time in milliseconds for the mock so the response will be delayed. The delay set here superseeds the delay defined in the response mock.

echoRequest(name, indicator)

Sets the indicator which enables / disables the request logging (only post request should be logged)

setAllScenariosToDefault()

Resets all mocks to the default scenarios

setAllScenariosToPassThrough

Resets all mocks to use passthroughs

setGlobalVariable(key, value)

Adds or updates the global key/value pair

setGlobalVariables(variables)

Adds or updates the global key/value pairs ie. {'some':'value', 'another': 'value'}

deleteGlobalVariable(key)

Remove the global variable matching the key

Howto use recording functionality

You can record API calls in NgApimock. This is usefull if you have a live API, and want to create mocks for them. You turn on Recording in the header Record (checkbox), and start calling the API. Requests are recorded for each mock. You can zoom in up to Request Response information. The response data can be used in mock files, described earlier.

Contributing

In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code committing.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].