ngx-mock-server
TypeScript icon, indicating that this package has built-in type declarations

2.0.1 • Public • Published

ngx-mock-server

npm version GitHub issues GitHub forks GitHub stars GitHub license

Inspired by ng2-mock-server

An angular 5+ mock to mock back-end. The package uses http client interceptors mechanism. It's a really useful package when real back-end isn't available.

Features

  • No back-end required 🚫
  • Support regexp and strings in routes definitions 📣
  • Support lazy modules 🐪
  • Works with Angular 5+ (including Angular 9) 💥
  • Can be disabled from outside 👮
  • Zero-dependency 0️⃣

Getting started

npm i ngx-mock-server

Mock necessary endpoints:

import { HttpRequest, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { RouteDeclaration, json } from 'ngx-mock-server';
 
const users = [
  { id: 1, username: 'user1' },
  { id: 2, username: 'user2' }
];
 
export function usersCallback(req) {
  const query = req.params.get('query');
  return json(200, [
    { id: 1, username: 'user1' },
    { id: 2, username: 'user2' }
  ]);
}
 
export const appMockRoutes: RouteDeclaration[] = [
  {
    path: '/users',
    method: 'GET',
    callback: usersCallback
  },
]

Import NgxMockServerModule with mocked endpoints:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { NgxMockServerModule } from 'ngx-mock-server';
import { appMockRoutes } from './mock';
import { HttpClientModule } from '@angular/common/http';
 
@NgModule({
  imports:      [ 
    BrowserModule,
    HttpClientModule,
    NgxMockServerModule.forRoot({
      routes: appMockRoutes,
      enabled: true
    })
  ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

Test!:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
 
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  constructor(private httpClient: HttpClient) {
  }
 
  ngOnInit() {
    this.httpClient.get('/users').subscribe((users) => console.log(users));
  }
}
 

StackBlitz

DEMO

Here

Readme

Keywords

none

Package Sidebar

Install

npm i ngx-mock-server

Weekly Downloads

10

Version

2.0.1

License

none

Unpacked Size

261 kB

Total Files

59

Last publish

Collaborators

  • dima11221122