npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

http-mocks

v1.3.2

Published

HTTP mocking library primarily targeted for the Angular applications

Downloads

776

Readme

http-mocks

npm version npm GitHub license Commitizen friendly

This HTTP mocking library (XHR and Fetch API) is an alternative version of awesome library data-mocks with a few additional features:

  • console logs of the requests and responses (loggingEnabled parameter in the MockOptions)

  • access to the body and query parameters of the request within the particular mock (so you can modify a response according to the request)

  • better support for the Angular applications, however, it stays framework agnostic:

    • option to accept location string after a hashtag (e.g. http://localhost:4200/#/?mockScenario=scenarioKey)
    • HttpMocksService to easily inject mocks into your app
  • option to set default response code, headers and, delay

  • works in IE11 (requires URLSearchParams polyfill):

    import 'core-js/features/url-search-params';

Lots of code in this library is heavily inspired by the code of the data-mocks library. So huge thanks to the authors! See Dave's Cooper great talk about mocking with data-mocks.

Angular versions compatibility

| Angular | http-mocks | | ------- | ---------- | | 9.x | 1.x | | 8.x | 0.x |

Examples

Read the blog post or see it in action.

Instalation

  • Install the package in your project as a dependency:
npm install http-mocks --save-dev

Usage (Angular)

  • Setup the http-mocks provider:
import { Provider, APP_INITIALIZER } from '@angular/core';

import {
  HttpMocksService,
  MockScenarios,
  RequestQuery,
  RequestBody
} from 'http-mocks';

export const httpMocksProvider: Provider = {
  provide: APP_INITIALIZER,
  useFactory: httpMocksProviderFactory,
  deps: [HttpMocksService],
  multi: true
};

// Create factory function for the http-mocks provider
function httpMocksProviderFactory(httpMocksService: HttpMocksService) {
  return () =>
    httpMocksService.setHttpMocks(mocks, {
      loggingEnabled: true,
      useLocationHash: true
    });
}

// Prepare mocks at least for the `default` scenario
const mocks: MockScenarios = {
  default: [
    {
      url: /getUserInfo/,
      method: 'POST',
      responseFn: (requestQuery: RequestQuery, requestBody: RequestBody) => {
        return {
          userId: requestBody.userId,
          firstName: 'John',
          lastName: 'Doe'
        };
      },
      delay: 1500,
      responseCode: 200
    }
  ]
};
  • Add the http-mocks provider to your app.module.ts:
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

import { environment } from '../environments/environment';

@NgModule({
  declarations: [AppComponent],
  imports: [
    ...
  ],
  providers: [
    ...(environment.production ? [] : [httpMocksProvider])
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

Usage (regardless of the framework)

  • Import the injectHttpMocks function into your project and use it:
import { injectHttpMocks, RequestQuery, RequestBody } from 'http-mocks';

injectHttpMocks(
  {
    default: [
      {
        url: /getUserInfo/,
        method: 'POST',
        responseFn: (requestQuery: RequestQuery, requestBody: RequestBody) => {
          return {
            userId: requestBody.userId,
            firstName: 'John',
            lastName: 'Doe'
          };
        },
        delay: 1500,
        responseCode: 200
      }
    ]
  },
  {
    loggingEnabled: true,
    useLocationHash: true
  }
);

Mocks & Options

(within the setHttpMocks method of the HttpMocksService, or injectHttpMocks function itself)

setHttpMocks(mockScenarios: MockScenarios, mockOptions: MockOptions) {
  injectHttpMocks(mockScenarios, mockOptions);
}

Mock (Mock Scenarios)

MockScenarios object contains user-defined arrays of mocks (Mock[]). Each array represents one scenario. A particular scenario should be selected either via mockScenario parameter in the MockOptions or via query parameter ?mockScenario in the URL of the running application.

interface Mock {
  /**
   * A regular expression that should match with the URL of the HTTP request.
   */
  url: RegExp;

  /**
   * HTTP method.
   */
  method: HttpMethod;

  /**
   * A function that contains a logic that returns response data accordingly to the request (query params and payload).
   */
  responseFn: (requestQuery: RequestQuery, requestBody: RequestBody) => any;

  /**
   * Status code of the HTTP transaction. (default: `200`)
   */
  responseCode?: number;

  /**
   * Headers of the response. (default: `{}`)
   */
  responseHeaders?: ResponseHeaders;

  /**
   * Time of the response delay (in milliseconds). (default: `0`)
   */
  delay?: number;
}

Mock Options

interface MockOptions {
  /**
   * Whether pass through the request to the network if no mock exists. (default: `true`)
   */
  fallbackToNetwork?: boolean;

  /**
   * Whether log information about request/response of the mock to the console. (default: `false`)
   */
  loggingEnabled?: boolean;

  /**
   * Whether accept search string placed after the hashtag in URL,
   * e.g. `http://localhost:4200/#/?mockScenario=scenarioKey`. (default: `false`)
   */
  useLocationHash?: boolean;

  /**
   * The scenario key to use for mocking. (default: `'default'`)
   */
  mockScenario?: keyof MockScenarios;

  /**
   * Common response code for all mocks that can be overridden by the response code of the particular mock. (default: `200`)
   */
  defaultResponseCode?: number;

  /**
   * Common response headers for all mocks that can be overridden by the response headers of the particular mock. (default: `{}`)
   */
  defaultResponseHeaders?: ResponseHeaders;

  /**
   * Common mock delay for all mocks that can be overridden by the mock delay of the particular mock. (default: `0`)
   */
  defaultDelay?: number;

  /**
   * Wrapper function that applies to all mock responses.
   * Useful when you change the overall data response structure without an impact on the data.
   */
  responseProxyFn?: (
    responseBody: any, // The result of the `responseFn: (requestQuery: RequestQuery, requestBody: RequestBody) => any`
    mockParams: MockParams,
    mockRequest: MockRequest
  ) => MockResponse;

  /**
   * Disables specific mocks.
   * With this option, you can easily disable particular mocks when you're about to connect to the real API.
   */
  ignoredMocks?: RegExp[];
}