http-mocks
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 theMockOptions
) -
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 accept location string after a hashtag (e.g.
-
option to set default response code, headers and, delay
-
works in IE11 (requires
URLSearchParams
polyfill):;
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:
; ; ; // Create factory function for the http-mocks provider // Prepare mocks at least for the `default` scenario;
- Add the
http-mocks
provider to yourapp.module.ts
:
; ; ;
Usage (regardless of the framework)
- Import the
injectHttpMocks
function into your project and use it:
; injectHttpMocks , ;
Mocks & Options
(within the setHttpMocks
method of the HttpMocksService
, or injectHttpMocks
function itself)
setHttpMocksmockScenarios: MockScenarios, mockOptions: 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.
Mock Options