UNPKG

@nodifier/http-mock

Version:

A node module to mock http/https requests made for unit testing etc.

112 lines (63 loc) 1.84 kB
# @nodifier/http-mock A node module to mock http/https requests made for unit testing etc. Suitable for unit testing framework like Jest. ## How to use? ```typescript import { justMock } from '@nodify/http-mock'; describe('some unit tests', () => { it('should mock the request', async () => { const jm = justMock('http://example.com/api').get(200).response('hello world') // Your node request function that you wish to mock the request const output = await makeRequest(); jm.done(); expect(output).toStrictEqual('hello world'); }) }) ``` ### Specify the endpoint to mock ```typescript // The endpoint to mock jestMock('http://example.com/api') ``` ### Mocking the response status code You can mock the response from any of the request methods available. [view](#supported-request-methods) ```typescript // response status code to mock as a response get(200) ``` ### Mocking the response body The response body can be mock by using the `response` method as follows: ```typescript // Will return "hello world" as the request response response('hello world'); ``` ### Ending mock The mock always have to be ended with `done` method when the unit test is done like follows... ```typescript const jm = justMock('http://example.com/api').get(200).response('hello world') const output = await makeRequest(); // Ends the mock jm.done(); expect(output).toBeTruthy(); ``` ## Supported request methods 1. [GET](#get) 2. [POST](#post) 3. [PUT](#put) 4. [DELETE](#delete) ### GET ```typescript justMock('http://example.com/api').get(200) ``` ### POST ```typescript justMock('http://example.com/api').post(200) ``` ### PUT ```typescript justMock('http://example.com/api').put(200) ``` ### DELETE ```typescript justMock('http://example.com/api').del(200) ```