server-mocker

    1.6.3 • Public • Published

    server-mocker

    Create a mocked http server for your webapp tests and development

    Install

    If you use npm:

    npm install --save-dev server-mocker
    

    If you use yarn:

    yarn add --dev server-mocker
    

    Examples

    Testing

    You have a webapp with the following code:

    export const getUserData = (userId) =>
      fetch(`http://localhost:5000/user?id=${userId}`).then((res) => res.json());

    You want to write a test for that code and you need to mock the server response. You can use server-mocker

    import {getUserData} from '../api';
    import {createServer, json} from 'server-mocker';
    
    const mockingServer = createServer({port: 5000});
    
    const requestUser = (expectedUserId) => (request) =>
      request.urlPath === '/user' && urlParams.id === expectedUserId;
    
    test('getUserData', async () => {
      const userId = 'any_user_id';
      const userData = {
        name: 'Abel',
      };
    
      mockingServer.stub(requestUser(userId)).returns(json(userData));
    
      const userData = await getUserData(userId);
    
      expect(userData.name).toBe('Abel');
    });

    Dev api server

    You can also use server-mocker as a development api server running a small node script:

    dev-api.js

    import {createServer, json} from 'server-mocker';
    
    const mockingServer = createServer({port: 5000});
    
    const requestUser = (request) => request.urlPath === '/user';
    
    mockingServer.stub(user()).returns(
      json({
        name: 'Abel',
      })
    );
    node dev-api.js
    

    In your application you can change your api endpoint depending on process.env.NODE_ENV

    const API_ENDPOINT =
      process.env.NODE_ENV === 'production' ? 'http://my-real-api.com/' : 'http://localhost:5000';
    
    export const getUserData = (userId) => fetch(`${API_ENDPOINT}/user?id=${userId}`).then((res) => res.json());

    API

    createServer(options)

    Creates an http(s) server instance where you can mock/stub responses

    Parameters

    • options: Object
      • port?: number the server will run in this port. If not provided, the server will use a random available port. You can then read it with server.port
      • ssl?: Object you can pase an object with ssl options to use https. When not specified, the server will use http
      • onResponseNotFound?: (r: Request) => mixed You can specify a listener to be called when a the server receives a server which doesn't know how to reply to.

    Returns: MockingServer

    Examples

    const mockingServer = createServer();

    using a given port:

    const mockingServer = createServer({port: 5000});

    with ssl:

    const mockingServer = createServer({
      port: 5000,
      ssl: {
        key: fs.readFileSync(__dirname + '/server.key'),
        cert: fs.readFileSync(__dirname + '/server.crt'),
      },
    });

    MokingServer

    .stub(predicate)

    Configures a stubbed response for the requests that match the given predicate

    Parameters

    • predicate: (r: Request) => boolean

    Returns: Object with key:

    Example

    import {createServer, text} from 'server-mocker';
    
    const mockingServer = createServer({port: 5000});
    
    // A request predicate wich matches when url has the expected params
    const withUrlParams = (expectedUrlParams) => (request) =>
      Object.keys(expectedUrlParams).every(
        (paramName) => request.urlParams[paramName] === expectedUrlParams[paramName]
      );
    
    // Stub the server to return the text "pong" when a request with ?message=ping is received
    mockingServer.stub(witUrlParams({message: 'ping'})).returns(text('pong'));

    .mock(predicate)

    Similar to .stub, the difference is you can make expectations for received requests

    Parameters

    • predicate: (r: Request) => boolean

    Returns: Object with key:

    Example

    const mock = mockingServer.mock(witUrlParams({message: 'ping'})).returns(text('pong'));

    .mockImplementation(predicate, fn)

    If you need more control, you can use mockImplementation, instead of providing a return value, you provide a function that is called with the matching request and should return a response.

    Parameters

    Returns: Stub

    Example

    mockingServer.mockImplementation(witUrlParams({message: 'ping'}), (request) => {
      return text(String(Math.random()));
    });

    .clearAll()

    Removes all the stubs and mocks from the server.

    Example

    mockingServer.clearAll();

    .close()

    Removes all the stubs and mocks from the server and closes the server connection.

    Example

    mockingServer.close();

    .port

    (number) the server port.

    Stub

    A Stub (returned by .stub().returns() calls) is an object with the method:

    .clear()

    Removes the stub from the server

    Mock

    A Mock (returned by .mock().returns() calls) is an object with the methods:

    .clear()

    Removes the mock from the server

    .called()

    Returns true when at least one request has been handled by the server matching this mock

    .calledOnce()

    Returns true when one and only one request has been handled by the server matching this mock

    .getCallCount()

    Returns number the number of request handled by the server matching this mock

    Request

    It's an object with these fields:

    • method: string http method ('GET', 'POST', 'PUT'...)
    • urlPath: string the url path, for example '/about'
    • urlParams: Object a key-value object with url params
    • formFields: Object a key-value object with form fields
    • headers: Object a key-value object with request headers

    Response

    It's an object with these fields:

    • content: string http response content
    • headers: Object a key-value object with request headers
    • statusCode: number http status code (200, 404, 302...)

    text(content, [headers])

    Creates a response with content type 'text/plain' and with the given content and optional headers

    Parameters

    • content: string
    • headers?: headers

    Returns Response

    html(content, [headers])

    Creates a response with content type 'text/html' and with the given content and optional headers

    Parameters

    • content: string
    • headers?: headers

    Returns Response

    json(data, [headers])

    Creates a response with content type 'application/json' and with the given data and optional headers

    Parameters

    • data: mixed this data is json-encoded into response's content
    • headers?: headers

    Returns Response

    Keywords

    none

    Install

    npm i server-mocker

    DownloadsWeekly Downloads

    2

    Version

    1.6.3

    License

    MIT

    Unpacked Size

    28.4 kB

    Total Files

    7

    Last publish

    Collaborators

    • atabel